/* */ Click to Join Live Class with Shankar sir Call 9798158723

Input/Output files in C ?


There are three types of I/O function to read from or write to the file.
  • File I/O Function for fscanf() and fprintf()
  • File I/O Function for string fgets() and fputs()
  • File I/O function for characters fgetc() and fputc()

fscanf()

The function of fscanf and scanf are exactly same only change is that scanf is used to get data input from keyboard where fscanf is used to get data from the file pointed to by fp because input is read from the file .


Syntax:-
fscanf(fp,”format string”,list);

Where,
  • fp is file pointer it can point to a sourse file or standard input if fp is pointing to stdin data is read from the keybord.
  • Format sring and list :- it have the same meaining as in scanf() i.e the variables specified in the list will take the values form the file specified by fp using the specifications provided in format string.
  • The function return EOF when it attempts to read at the end of the file otherwise it return the number of items read in and successfully converted.

Example if we would like to enter name roll :-
fscanf(fp,”%s,%d”,name,&roll);
fprintf(); is same as printf() but basic difference it give output form file .

Program of read from keyboard and write into file.
 #include<stdio.h>
 #include<stdlib.h>
 void main()
 {
 FILE *fp;
 int n;
 fp=fopen(“input.txt”,”w”);    //  open the file in write mode 
 if(fp==NULL)
 {
 printf(“error in opening the file”);
 exit();
 }
 while(scanf(“%d”,&n)!=EOF)
 {
 fprintf(fp,”%d”,n);
 }
 fclose(fp);
 }