So I'm currently learning file processing for my assignment, and I'm wondering why this code
#include<stdio.h>
int main(){
char test[255];
FILE *open;
open = fopen("data.txt", "r");
while(fscanf(open, "%s", test)!=EOF){
printf("%s", test);
}
}
works while the following one
#include<stdio.h>
int main(){
char test[255];
FILE *open;
open = fopen("data.txt", "r");
fscanf(open,"%s", test);
printf("%s", *test);
}
didn't, any answer would be appreciated!
CodePudding user response:
On success, the fscanf() function returns the number of values read and on error or end of the file it returns EOF or -1
Now if you do not put this function inside a while loop, it will read one character only. Essentially we want it to run as long as there is data to read inside the text file so we put it inside a while loop, so as long as the file has data to read, it will not return an EOF or a -1 so it will keep on executing and read the data from the file.
For further explanation check fscanf() Function in C
