Wednesday, March 9, 2016

C program for creating, deleting and display records of an employee dynamically

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 200
struct emp
{
    int id;
    char *name;
}*emp1, *emp3;
void display();
void create();
FILE *fp, *fp1;
int count = 0;
void main()
{
    int i, n, ch;
    printf("1 Create a Record\n");
    printf("2 Display Records\n");
    printf("3 Exit");
    while (1)
    {
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
           //opening file into append mode
   fp = fopen("emp.txt", "a");
   create();
   break;
case 2:
           //opening file into read binary mode
   fp1 = fopen("emp.txt","rb");
   display();
   break;
case 3:
          //passing 0 to exit means success-convention
           exit(0);
       default:
           printf("please enter a correct choice");
}
    }
}
void create()
{
    int i;
    char *p;
    emp1 = (struct emp *)malloc(sizeof(struct emp));
    emp1->name = (char *)malloc((size)*(sizeof(char)));
    printf("Enter name of employee : ");
    scanf(" %[^\n]s", emp1->name);
    printf("Enter emp id : ");
    scanf(" %d", &emp1->id);
    fwrite(&emp1->id, sizeof(emp1->id), 1, fp);
    fwrite(emp1->name, size, 1, fp);
    count++;
    fclose(fp);
}
void display()
{
    int i=1;
    emp3=(struct emp *)malloc(1*sizeof(struct emp));
    emp3->name=(char *)malloc(size*sizeof(char));
    if (fp1 == NULL)
    printf("\nFile not opened for reading"); //if there is some error in opening file
    while (i <= count)
    {
fread(&emp3->id, sizeof(emp3->id), 1, fp1);
fread(emp3->name, size, 1, fp1);
printf("\n%d %s",emp3->id,emp3->name);
i++;
    }
    fclose(fp1);
    free(emp3->name);
    free(emp3);
}


output:
 1 Create a Record
 2 Display Records
 3 Exit
Enter your choice :1
Enter name of employee :emp1
Enter emp id :1

Enter your choice :1
Enter name of employee :emp2
Enter emp id :2

Enter your choice :2
1 emp1
2 emp2

Enter your choice :3

1 comment: