我想用C编写一个程序,只需读取一个文件,将其存储到数组中,然后打印数组。一切都很好,但当文本文件有多行时,我总是只打印出最后一行。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * stream;
char dateiname[255];
stream = fopen("heute.txt", "r");
if(stream == NULL){
printf("Error");
}else {
while(!feof(stream)){
fgets(dateiname, 255, stream);
}
fclose(stream);
}
printf("%sn", dateiname);
}
谢谢你的帮助!
-
一切都很好,但当文本文件有多行时,我总是只打印出最后一行
原因:对于每次迭代,数据都会被下一行数据替换,并且在末尾dateiname
将只读取最后一行。
-
while(!feof(stream((
不建议使用feof()
。有关详细信息,请参阅此链接:https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&答案=1046476070
-
请参阅以下代码:
#include <stdio.h> #include <stdlib.h> int main() { FILE *stream; char dateiname[1024]; int i = 0; stream = fopen("heute.txt", "r"); if (stream == NULL) { printf("Error"); } else { while (fgets(dateiname, sizeof(dateiname), stream) != NULL) { printf("Line %4d: %s", i, dateiname); i++; } } return 0; }
如果您只想读取和打印文件的内容,则无需担心文件的大小和文件中的行数。
您可以在while
中运行fgets()
并打印每一行,直到我们到达NULL
但是,如果您想存储它们,我们需要计算文件的大小。因此,我们需要使用像stat
或fstat
这样的函数来获得文件的大小并动态分配内存,然后只使用read
那么多字节。