程序读取文件最后一行两次
Program Reading Last Line of File Twice
我正在编写一个逐行读取 .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))
错误,您最终 "eating" 文件结尾。你应该做
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
// process the line
}
相关:Why is iostream::eof inside a loop condition considered wrong?
eof
读取最后一行后设置文件指示器。
while(!feof(textFile))
{
fgets(buffer, MAX_LINELENGTH, textFile); //Gets a line from file
请更正以上代码片段如下:
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
我正在编写一个逐行读取 .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))
错误,您最终 "eating" 文件结尾。你应该做
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
// process the line
}
相关:Why is iostream::eof inside a loop condition considered wrong?
eof
读取最后一行后设置文件指示器。
while(!feof(textFile))
{
fgets(buffer, MAX_LINELENGTH, textFile); //Gets a line from file
请更正以上代码片段如下:
while(fgets(buffer, MAX_LINELENGTH, textFile))
{