我正在编写一个逐行读取.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: %sn", buffer);
}
}
while(!feof(textFile))
是错误的,你最终会"吃掉"文件的末尾。你应该做
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
// process the line
}
相关:为什么循环条件内的iostream::eof被认为是错误的?
eof
文件指示集读取最后一行后
while(!feof(textFile))
{
fgets(buffer, MAX_LINELENGTH, textFile); //Gets a line from file
请更正以上代码片段如下:
while(fgets(buffer, MAX_LINELENGTH, textFile))
{