0

I write c program that reads a file (argv1) line by line

my text file is this :

enter image description here

This is my code

#include <stdio.h>
#include <stdlib.h>

void read_fp(FILE *fp){
        char buffer[50];
        fgets(buffer, sizeof(buffer), fp);
        printf("%s", buffer);

}


int main(int argc, char* argv[]){
        FILE* fp = fopen(argv[1], "r");
        while(1){
                if(feof(fp)) break;
                read_fp(fp);
        }
        return 0;
}

OR

int main(int argc, char* argv[]){
        FILE* fp = fopen(argv[1], "r");
        while(!feof(fp)){
                read_fp(fp);
        }
        return 0;
}

I predict my program prints one two three four five six

but program actually prints one two three four five six six

it loops once more

why...? how can i fix this

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
skk
  • 67
  • 4
  • 1
    [Don't use `feof`](https://stackoverflow.com/questions/5431941). To detect the end-of-file, look at what `fgets` returns. If `fgets` returns `NULL`, then it didn't read anything from the file. – user3386109 Apr 17 '21 at 09:36

1 Answers1

1

After reading the last record of the file the condition feof( fp ) is not set yet.

So within the function you are trying to access the file one more

void read_fp(FILE *fp){
        char buffer[50];
        fgets(buffer, sizeof(buffer), fp);
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        printf("%s", buffer);

}

In this case the condition is satisfied and the call of fgets returns NULL. But you are outputting the current value stored in buffer that results in undefined behavior.

You could change the function for example like

void read_fp(FILE *fp){
        char buffer[50];
        If ( fgets(buffer, sizeof(buffer), fp) ) printf("%s", buffer);
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335