0

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 <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);
    }
}
Jonny Henly
  • 3,725
  • 4
  • 23
  • 41
Coder Billy
  • 11
  • 1
  • 3

2 Answers2

2
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?

Community
  • 1
  • 1
vsoftco
  • 52,188
  • 7
  • 109
  • 221
1

eof file indicator set after read the last line.

while(!feof(textFile))
{
    fgets(buffer, MAX_LINELENGTH, textFile); //Gets a line from file

Please correct above code snippet as follows:

while(fgets(buffer, MAX_LINELENGTH, textFile))
{
Steephen
  • 11,597
  • 6
  • 29
  • 41