English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structures

C Language Files

C Others

C Language Reference Manual

C File fprintf() and fscanf()

Write to file: fprintf() function

The fprintf() function is used to write a character set to a file. It sends formatted output to the stream.

Syntax:

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

#include <stdio.h> 
void main() {
   FILE *fp;
   fp = fopen("file.txt", "w");//Open file
   fprintf(fp, "I am the data written by fprintf...\n");//Write data to file
   fclose(fp);//Close file
}

Read file: fscanf() function

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

Syntax:

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

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

Output:

I am the data written by fprintf...

C File Example: Store Employee Information

Let's look at a file handling example that stores employee information entered by the user from the specified console. We will store the employee's ID, name, and salary.

#include <stdio.h> 
void main() {
    FILE *fptr;
    int id;
    char name[30];
    float salary;
    fptr = fopen("emp.txt", "w");+");/*  Open file in write mode */
    if (fptr == NULL)
    {
        printf("File does not exist\n");
        return;
    }
    printf("Enter id\n");
    scanf("%d", &id);
    fprintf(fptr, "Id= %d\n", id);
    printf("Enter name\n");
    scanf("%s", name);
    fprintf(fptr, "Name= %s\n", name);
    printf("Enter salary\n");
    scanf("%f", &salary);
    fprintf(fptr, "Salary= %s.", salary);2f\n", salary);
    fclose(fptr);
}

Output:

Enter id 
1
Enter Name 
sonoo
Enter Salary
120000

Now open the file from the current directory. For Windows operating system, please go to the file directory, where you will see the emp.txt file. It will have the following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000