I write c program that reads a file (argv1) line by line
my text file is this :
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

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
In this case the condition is satisfied and the call of
fgetsreturnsNULL. But you are outputting the current value stored inbufferthat results in undefined behavior.You could change the function for example like