C Program to create a file & store information of a person

March 26, 2022, Learn eTutorial

What is a file in C?

A file is simply a collection of bytes stored in a storage device like tape, magnetic disc, optical disc, etc.  We can use the fopen() function to open or create a new file. Similarly, we use the fclose() function to close the file. Given below is the code of the C program to create files and store information.  here we have to create a file and store information about a person in terms of his name, age, and salary.

Which are the critical operations performed on a file in C?

Different Operations can be performed on a File. Important among them are listed below.

  1. Making of a new File
  2. Opening an existing File using fopen
  3. Reading data from the File using fscanf or fgetc
  4. Writing data to a File using fputs or fprintf
  5. Moving the File to a specific location using fseek or rewind
  6. Closing of the File using fclose


STEP 1: Include the header files to use the built-in functions in the C program.

STEP 2: Declare the variable *ftpr as of type FILE, declare the name as a character, age as an integer, salary as a float.

STEP 3: Open the File using the function fopen() with write permission.

STEP 4: If fpr=null, then the display file does not exist. Otherwise, do step 5.

STEP 5: Read the name from the user and save it into the variable name then write it into the File using the function fprintf.

STEP 6: Read the age from the user and save it into the variable age then write it into the File using function fprintf.

STEP 7: Read the salary from the user and save it into the variable salary then write it into the File using function fprintf.

STEP 8: Close the file using fclose().

To create and write data into a file using the C program, we need to understand the below topics, please refer to these topics.

C Source Code

                                          #include <stdio.h>

void main() {
  FILE * fptr;
  char name[20];
  int age;
  float salary;
  fptr = fopen("emp.rec", "w"); /*open for writing*/
  if (fptr == NULL) {
    printf("File does not exists\n");
  printf("Enter the name\n");
  scanf("%s", name);
  fprintf(fptr, "Name    = %s\n", name);
  printf("Enter the age\n");
  scanf("%d", & age);
  fprintf(fptr, "Age     = %d\n", age);
  printf("Enter the salary\n");
  scanf("%f", & salary);
  fprintf(fptr, "Salary  = %.2f\n", salary);


Enter the name

Enter the age

Enter the salary
Please note that you have to open the file called emp.rec in the directory
Name    = Ajay
Age       = 25
Salary   = 25000.00