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

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this c program, we have to create a file and store information about a person in terms of his name, age, and salary. In other words, we can say that this c program demonstrates the file creation and writing data into that file.

What is a file in C?

A file is simply a sequence of bytes. 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. It is a simple c program to understand, and here it only uses simple library functions. A file is simply a collection of bytes stored in a storage device like tape, magnetic disc, optical disc, etc. To store information, we have to use a file.

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

ALGORITHM

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().

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");
    return;
  }
  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);
  fclose(fptr);
}
                                      

OUTPUT

Enter the name
Ajay

Enter the age
25

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