loop once more in C

88 views Asked by At

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

1

There are 1 answers

0
Vlad from Moscow On

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);
}