C Program to Create a File and Store Information

This C Program creates a file & store information. We frequently use files for storing information which can be processed by our programs. In order to store information permanently and retrieve it we need to use files and this program demostrate file creation and writing data in that.

Here is source code of the C program to create a file & store information.The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C program to create a file called emp.rec and store information
  3.  * about a person, in terms of his name, age and salary.
  4.  */
  5. #include <stdio.h>
  7. void main()
  8. {
  9.     FILE *fptr;
  10.     char name[20];
  11.     int age;
  12.     float salary;
  14.     /*  open for writing */
  15.     fptr = fopen("emp.rec", "w");
  17.     if (fptr == NULL)
  18.     {
  19.         printf("File does not exists \n");
  20.         return;
  21.     }
  22.     printf("Enter the name \n");
  23.     scanf("%s", name);
  24.     fprintf(fptr, "Name    = %s\n", name);
  25.     printf("Enter the age\n");
  26.     scanf("%d", &age);
  27.     fprintf(fptr, "Age     = %d\n", age);
  28.     printf("Enter the salary\n");
  29.     scanf("%f", &salary);
  30.     fprintf(fptr, "Salary  = %.2f\n", salary);
  31.     fclose(fptr);
  32. }

$ cc pgm95.c
$ a.out
Enter the name
Enter the age
Enter the salary

Sanfoundry Global Education & Learning Series – 1000 C Programs.


Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on File Handling, go to C Programming Examples on File Handling . If you wish to look at programming examples on all topics, go to C Programming Examples.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.