fprintf() and fscanf()

Writing File : fprintf() function
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
int fprintf( FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>  
main(){  
FILE *fp;  
fp = fopen("file.txt", "w");   //opening file  
fprintf(fp, "Hello catchmecoder...\n");   //writing data into file  
fclose(fp);   //closing file  
  } 

Reading File : fscanf() function

The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.
Syntax:

int fscanf(FILE *stream, const char *format [, argument, ...])
Example:
#include <stdio.h>  
 main() {  
FILE *fp;  
char buf[250];   //creating char array to store data of file  
fp = fopen("file.txt", "r");  
while(fscanf(fp, "%s", buf)!=EOF){  
printf("%s ", buf );  
 }  
fclose(fp);  
  }
Output:

Hello catchmecoder...  

File Example: Storing student information

see a file handling example to store employee information as entered by user from console. We are going to store id, name and balance of the student.
#include <stdio.h>  
 void main() {  
FILE *fptr;  
int id;  
char name[30];  
float balance;  
fptr = fopen("emp.txt", "w+");  /*  open for writing */  
if (fptr == NULL) {  
printf("File   exists \n");  
return;  
 }  
printf("Enter the id\n");  
scanf("%d", &id);  
fprintf(fptr, "Id= %d\n", id);  
printf("Enter the name \n");  
scanf("%s", name);  
fprintf(fptr, "Name= %s\n", name);  
printf("Enter the balance\n");  
scanf("%f", &balance);  
fprintf(fptr, "balance= %.2f\n", balance);  
fclose(fptr);  
  }  
Output:
Enter the id 
5
Enter the name 
Pramesh
Enter the balance
50000  
Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.
Id= 5
Name= Pramesh
Balance= 50000