C语言 从文件中读取并存储在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4237084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:08:15  来源:igfitidea点击:

Reading from a file and storing in array

crandom

提问by razor35

I've written the following program to read line by line from a file and store it in the words array. The output should be two random words from the array. But surprisingly the words array contains only the last word read repeatedly. Any help on what went wrong?

我编写了以下程序来从文件中逐行读取并将其存储在 words 数组中。输出应该是数组中的两个随机单词。但令人惊讶的是, words 数组只包含重复读取的最后一个单词。对出了什么问题有帮助吗?

int main(){
 int i = 0;
 char line_buffer[BUFSIZ];
 char* words[20];
 FILE *fp = fopen("input.txt", "r");
  while (fgets(line_buffer, sizeof(line_buffer), fp)) {
  //printf("%s", line_buffer); 
  words[i] = line_buffer;
  i = i + 1;
 } 
 printf("%d", i);
 int j = rand()%8;
    int k = (j+1)%8;
 printf("%s %s", words[j], words[k]); 
 fclose(fp);
 return 0;
}

input.txt

输入文件

nematode knowledge
empty bottle
nevertheless
claustrophobia
metamorphosis
acknowledgement
impossibility
never gave up

回答by Jonathan Leffler

You read each line of data into the same buffer, so the last line overwrites all previous lines. You're going to have to allocate space for each line by some means or other - either dynamic memory allocation with malloc()(or possibly strdup()), or using a fixed size array (which limits the amount of data your program can handle safely). You'll also need to deal with newlines in the data read.

您将每一行数据读入同一个缓冲区,因此最后一行会覆盖之前的所有行。您将不得不通过某种方式为每一行分配空间 - 使用malloc()(或可能strdup())动态内存分配,或使用固定大小的数组(这限制了您的程序可以安全处理的数据量)。您还需要处理读取的数据中的换行符。

You get some credit for using fgets()and not using gets(); that is a 100% correct decision.

你会因为使用fgets()和不使用而获得一些荣誉gets();这是一个 100% 正确的决定。



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

enum { MAXLINES = 30 };

int main(void)
{
    int i = 0;
    char lines[MAXLINES][BUFSIZ];
    FILE *fp = fopen("input.txt", "r");

    if (fp == 0)
    {
        fprintf(stderr, "failed to open input.txt\n");
        exit(1);
    }
    while (i < MAXLINES && fgets(lines[i], sizeof(lines[0]), fp))
    {
        lines[i][strlen(lines[i])-1] = '
int main(){
 int i = 0;

 int BUFSIZE = 1000;
 char* words[20];
 FILE *fp = fopen("input.txt", "r");
 if (fp == 0){
        fprintf(stderr, "Error while opening");
        exit(1);
 }

 words[i] = malloc(BUFSIZE);
  while (fgets(words[i], BUFSIZE, fp)) {
        i++;
        words[i] = malloc(BUFSIZE);
 } 
 printf("Output: \n");
 srand(time(NULL));
 int j = rand()%i;
 int k = (j+1)%i;
 fflush(stdout);
 printf("%d - %s %d -%s", j, words[j], k, words[k]); 

 int x;
 for(x = 0; x<i; x++)
       free(words[x]);
 scanf("%d", x);
 fclose(fp);
 return 0;
}
'; i = i + 1; } fclose(fp); printf("%d\n", i); srand(time(0)); int j = rand() % i; int k = (j+1) % i; printf("%s %s\n", lines[j], lines[k]); return 0; }

This checks that the file was opened successfully, closes the file as soon as the reading is complete, and ensures that it does not trigger a stack overflow by reading more lines than the array can hold. It wastes a lot of space by over-allocating space so each line could be very long (though the lines are typically quite short). If a line is longer than BUFSIZ, it will be read into a couple of adjacent entries in lines. It does not assume that there are 8 lines in the data file. It zaps the newline at the end of each line (unless a line is split, in which case it zaps the last character before the split on the first of the two lines). It seeds the random number generator with the current time. It seems odd that you only ever want adjacent lines from the file.

这会检查文件是否已成功打开,读取完成后立即关闭文件,并确保不会通过读取超过数组可容纳的行数来触发堆栈溢出。它通过过度分配空间浪费了大量空间,因此每行可能很长(尽管这些行通常很短)。如果一行比 BUFSIZ 长,它将被读入lines. 它不假设数据文件中有 8 行。它在每行的末尾换行(除非一行被拆分,在这种情况下,它会在两行中的第一行拆分之前的最后一个字符)。它将当前时间作为随机数生成器的种子。您只想要文件中的相邻行似乎很奇怪。

回答by SuperJulietta

##代码##

ps. Check malloc result

附:检查 malloc 结果

回答by thammi

You repeatedly overwrite the memory in line_buffer. The words array contains only pointers this variable.

您反复覆盖 line_buffer 中的内存。words 数组只包含这个变量的指针。

You should either use a multi-dimensional array or allocate memory at runtime.

您应该使用多维数组或在运行时分配内存。

Btw: Bad things will happen when you pass more than 20 lines to your code ...

顺便说一句:当你向你的代码传递超过 20 行时会发生不好的事情......

回答by Eli Bendersky

Did you initialize the random number generator with srand? An explanation, with an example of how to use it is available here.

您是否使用 初始化了随机数生成器srand此处提供了说明以及如何使用它的示例。