the printf statement here only prints out the last word inside of the file. Why is that?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE *fp;
int c;
char string[100];
fp = fopen("exam.txt", "r");
c = getc(fp);
while(c!=EOF)
{
fscanf(fp, "%s", string);
c = getc(fp);
}
fclose(fp);
printf("%s", string);
return 0;
}
Because you only print once at the end…
You need to print inside this loop:
if you want to see each line. You’re just overwriting
stringeach time.Also, you don’t initialize
int cbefore using it.Break down of
fscanf():Your loop condition is while the next character isn’t EOF meaning End Of File (a condition that happens after all the data has been read out of the file)
So:
You’ll note your algorithm doesn’t check for anything in that string, it just writes to it. This will overwrite the data in there each time. That’s why you only see the last line from your file, because you keep over writing
stringand the last thing in there happens to be the last line you read before seeing the EOF character and breaking out of the while loop.