This question already has answers here:
Closed 4 years ago.
Why is “while ( !feof (file) )” always wrong?
(4个答案)
我正在编写一个逐行读取
是错误的,你最终会“吃掉”文件的末尾。你应该这么做
相关:Why is iostream::eof inside a loop condition considered wrong?
(4个答案)
我正在编写一个逐行读取
.txt
文件的程序。到目前为止我已经做到了,但是文件的最后一行被读取了两次。我好像不明白为什么。提前谢谢你的帮助!这是我的密码:#include <stdio.h>
#include <string.h>
#define MAX_LINELENGTH 200
int main(int argc, char* argv[])
{
FILE* textFile;
char buffer[MAX_LINELENGTH];
char strName[40];
int numCharsTot;
int numWordsInMesg;
int numCharsInMesg;
textFile = fopen(argv[1], "r");
if(textFile == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
while(!feof(textFile))
{
fgets(buffer, MAX_LINELENGTH, textFile); //Gets a line from file
//printf("Got Line: %s\n", buffer);
}
}
最佳答案
while(!feof(textFile))
是错误的,你最终会“吃掉”文件的末尾。你应该这么做
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
// process the line
}
相关:Why is iostream::eof inside a loop condition considered wrong?
关于c - 程序两次读取文件的最后一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30540804/
10-12 14:47