fprintf() and fscanf()

fprintf() function : writing file

The fprintf() function is used to write set of character into file.

The syntax of fprintf() :

int fprintf(FILE *stream, const char *format [, argument, ...])

Let’s see the example of fprintf()

#include <stdio.h>  
main(){  
   FILE *fp;  
   fp = fopen("file.txt", "w");  
   fprintf(fp, "Hello file by fprintf...\n"); 
   fclose(fp);  
}

fscanf() function : Reading file

The fscanf() function used to read set of characters from the file.It read word from the file and return EOF end of the file.

The syntax of fscanf() :

int fscanf(FILE *stream, const char *format [, argument, ...])

Let’s see the example of fscanf()

#include <stdio.h>  
main(){  
   FILE *fp;  
   char buff[255]; 
   fp = fopen("file.txt", "r");  
   while(fscanf(fp, "%s", buff)!=EOF){  
   printf("%s ", buff );  
   }  
   fclose(fp);  
}

Output

Hello file by fprintf......

File Example

Let’s see the file handling example to store employee information as entered by user from console.

#include <stdio.h>  
void main()  
{  
    FILE *fptr;  
    int id;  
    char name[30];  
    float salary;  
    fptr = fopen("emp.txt", "w+");/*  open for writing */  
    if (fptr == NULL)  
    {  
        printf("File does not 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 salary\n");  
    scanf("%f", &salary);  
    fprintf(fptr, "Salary= %.2f\n", salary);  
    fclose(fptr);  
}

Output

Enter the id 
1
Enter the name 
Raj
Enter the salary
120000

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews