J Mei J Mei - 3 months ago 13
C Question

C - reading lines from file

I am trying to read line by line from a file and print out the line. But when I run the code, it starts printing out the lines starting in the middle.

char temp[300];

if (input == NULL) {
printf("Can't open input file.\n");
exit(-1);
}

while (!feof(input)) {
fgets(temp, 300, input);
printf("%s \n", temp);
}
fclose(input);


Any reason for it to start in the middle?

Edit: So and example of what I mean in the middle is that I have a list like this

7,12 Angry Men,1957
95,2001: A Space Odyssey,1968
211,8 and a Half,1963
190,A Beautiful Mind,2001
68,A Clockwork Orange,1971
223,A Fistful of Dollars,1964
108,A Separation,2011
233,A Streetcar Named Desire,1951
40,Alien,1979
58,Aliens,1986
96,All About Eve,1950
224,All Quiet on the Western Front,1930
250,All the President's Men,1976
91,Amadeus,1984
69,Amelie,2001
54,American Beauty,1999
33,American History X,1998
189,Amores Perros,2000


and when I get to the printf it only shows this

58,Aliens,1986
96,All About Eve,1950
224,All Quiet on the Western Front,1930
250,All the President's Men,1976
91,Amadeus,1984
69,Amelie,2001
54,American Beauty,1999
33,American History X,1998
189,Amores Perros,2000


Edit2: I made a change in the program to get rid of the \n in printf

while (fgets(temp, sizeof(temp), input) != NULL) {
printf("%s", temp);
}


and this fixed the problem. Is there any reason why the \n caused this problem?

Answer

Take a look to Why is “while ( !feof (file) )” always wrong?

fgets is enough:

while (fgets(temp, 300, input) != NULL) {
    printf("%s \n", temp);
}

Also, don't use magic numbers like 300, change to

while (fgets(temp, sizeof temp, input) != NULL) {
    printf("%s \n", temp);
}

it starts printing out the lines starting in the middle

Notice that fgets includes the trailing newline '\n' and you don't need to include it in the printf, do you mean this by "in the middle"?