Employee management using File in C
Question
Write a program for Employee management using File handling in C. Get the records from the user and store that in file.
Note
fseek() – used to move pointer to specific position
fwrite() – used to write in file
fread() – used to read from the file
For further details refer this
Logic
- The logic is simple for employee management. Create a structure for the employee with details such as name, job, salary, id.
- Get the employee details from the user.
- Open the file in w+(both reading and writing) mode and write the structure into the file using fwrite.
- To read the details, move the cursor to the beginning of the file and read each employee details using fread.
- Then print the employee details. You can also use fscanf, fprintf as alternative of fread, fwrite.
Program
#include<stdio.h> #include<stdlib.h> int main() { struct Emp { int id; char employeename[20]; long int salary; char job[20]; }e; int x; FILE* fptr; fptr = fopen("New.dat","w+"); //opening for both reading and writing if(fptr==NULL) printf("can't open file"); char c; do { printf("1.Insert new employee detail"); printf("\n\n2.Display all detail..."); scanf("%d",&x); getchar(); switch(x) { case 1: fseek(fptr,0,SEEK_END); //move cursor to end of file printf("\nEnter employee name: "); gets(e.employeename); printf("\nEnter employee id:"); scanf("%d",&e.id); getchar(); printf("\nEnter salary: "); scanf("%d",&e.salary); getchar(); printf("\nEnter job: "); gets(e.job); fwrite(&e, sizeof(struct Emp),1, fptr); break; case 2: fseek(fptr,0,SEEK_SET); //move cursor to the beginning of the file while(fread(&e,sizeof(struct Emp),1,fptr)) { printf("%d %s %d %s\n",e.id,e.employeename,e.salary,e.job); } break; default: printf("wrong choice"); } printf("Do you want to continue (y/n)..."); scanf("%c",&c); }while(c=='y'); fclose(fptr); //close the file }
You might also like…
Mini Cash Counter Application program in C