Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to create a file called emp.txt and store information about a person, in terms of his name, age and salary.

C Code Example — File Handling Programs

ADVERTISEMENT

C Program to create a file called emp.txt and store information about a person, in terms of his name, age and salary.

Objective

Write a C program to store formatted Employee records into a file.

Algorithm / Approach

  1. Create a file pointer and open "emp.txt" in Append mode ("a+").
  2. Read the name, age, and salary from the user.
  3. Use fprintf(fptr, "%s\n", name) to write the formatted string directly to the file.
  4. Do the same for age and salary.
  5. Close the file.
main.c
#include<stdio.h> 
int main( ) {
 FILE *fptr;
 char name[20];
 int age;
 float salary;
 fptr = fopen("emp.txt", "a+");
 if (fptr != NULL) {
  printf("Enter the name : ");
  scanf("%s", name);
  fprintf(fptr,"%s\n", name);
  printf("Enter the age : ");
  scanf("%d", &age);
  fprintf(fptr,"%d\n", age);
  printf("Enter the salary : ");
  scanf("%f", &salary);
  fprintf(fptr,"f\n", salary);
  fclose(fptr);
  printf("Record saved in File");
 }
 return 0;
}

Expected Output

Enter the name : Deepak
Enter the age : 24
Enter the salary : 30000.00
Record saved in File

Explanation of the Program

  • The fprintf() function is identical to printf(), but instead of printing to the console screen, it prints to a file pointer.
  • The "a+" mode stands for Append + Read. Unlike Write mode (which erases the file), Append mode preserves the existing file contents and adds the new data directly to the bottom of the file.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Typo in the format specifier. In the provided code snippet, fprintf(fptr,"f\n", salary); is missing the % sign before the f, which will just print the literal letter "f" into the file instead of the salary value!
ADVERTISEMENT