简体   繁体   English

C:无法将文件中的行存储到数组中

[英]C: Unable to store lines from a file into an array

This is some code I used to read and store lines from a text file into an "expressions" array: 这是一些我用来从文本文件中读取行并将其存储到“表达式”数组中的代码:

//create array for going through the file
char lines[128];
//create array for storing expressions
char **expressions = malloc(128*sizeof(char*));

FILE *file = fopen(argv[1],"r");
int count = 0;
while (fgets(lines,128,file)){
    expressions[count] = lines;
    printf("expressions[%d] is %s\n",count,expressions[count]);
    count++;
}

for (int i = 0; i<count; i++){
    printf("%s",expressions[i]);
}

And this is the text this code is trying to read: 这是此代码尝试读取的文本:

f = g + h - 42;
g = 12 + 23;

My issue here is that while it appears to go through the file properly (count matches the number of lines), the final print loop prints the last line g = 12 + 23 twice instead of the two distinct lines. 我的问题是,尽管它似乎可以正常浏览文件(计数与行数匹配),但最终的打印循环将最后一行g = 12 + 23两次打印,而不是两行不同。 Why is this occuring and what can I do to fix this issue? 为什么会发生这种情况,我该怎么做才能解决此问题?

Each time you read a line, you store it in the lines character array, and then you save the address of that array in the next space of expressions . 每次读取一行时,都将其存储在lines字符数组中,然后将该数组的地址保存在expressions的下一个空间中。 If you look at the values stored in expressions you'll find that they are all the same. 如果查看存储在expressions中的值,您会发现它们都是相同的。

If you want to keep a copy of each line, you're going to have to have space to store a copy of each line. 如果要保留每行的副本,则必须有空间存储每行的副本。 If you have a maximum number of lines which you're going to deal with, you can allocate that memory in the program. 如果您要处理的行数最大,则可以在程序中分配该内存。 Otherwise you're going to have to start using dynamic memory allocation. 否则,您将不得不开始使用动态内存分配。

Let's work on 100 lines maximum, with each line no longer than 127 characters (as above): 让我们最多处理100行,每行不超过127个字符(如上所述):

char expressions[100][128];

int count = 0;
while (fgets(lines,128,file)) {
    strcpy(expressions[count], lines);
    printf("expressions[%d] is %s\n",count,expressions[count]);
    count++;

    if (count == 100)
      break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM