Read data from file
fscanf() function is used to read data from file.
Syntax of fscanf() :
fscanf(file_pointer, format_specifier, variable);
Code example:
#include<stdio.h> int main() { FILE fp; fp=fopen("C://test.txt","w"); // open file in writing mode fprintf(fp,"KUET EEE"); fclose(fp); fp=fopen("C://test.txt","r"); // open file in reading mode char s[20]; fscanf(fp,"%s",s); printf("%s",s); return 0; }
Here first we open test.txt in writing mode and write “KUET EEE” text. Then retrieve first word “KUET” by
fscanf(fp,"%s",s);
Here s[20] can contain 19 character but why only “KUET” is retrieved by
fscanf(fp,"%s",s);
Here retrieving data has been terminated by space. Notice there is space between “KUET” and “EEE”.
So, How to read all data including space? is a big question.
We can do this by feof() function.
#include<stdio.h> int main() { FILE *fp; fp=fopen("C://test.txt","r"); while(feof(fp) ==0) { fscanf(fp,"%s",s); printf("%s\n",s); } return 0; }
feof() function will return non-zero value for any position of file except end of the file and zero value for the end position of file. File position is updated by file pointer fp.
Previous