I am writing a program that reads a .txt
file line by line. I have been able to do this so far, but the last line of the file is read twice. I can't seem to figure out why. Thank you for your help in advance! Here is the code I have:
#include
#include
#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);
}
}
Answer
while(!feof(textFile))
is wrong, you end up "eating" the end of file. You should do
while(fgets(buffer, MAX_LINELENGTH, textFile))
{
// process the line
}
Related: Why is iostream::eof inside a loop condition considered wrong?
No comments:
Post a Comment