Continuously storing worker details into file and displaying nth records


Question: Write a Program in C to continuously read name, age and salary of a worker and write it into a file until user confirms to end . Then read n from user and display the nth record in the file .

Program


#include<stdio.h>
#include<conio.h>
#include<string.h>

typedef struct
{
 char name[30];
 int age;
 int salary;
}worker;

int main()
{
 worker w[50];
 FILE *p;
 int i=0, n;
 char answer[5];
 clrscr();
 p = fopen("worker.txt", "wb+");
 if(p==NULL)
 {
  printf("File Error!");
  exit(1);
 }
 /* Reading records from users until user says "yes" */
 do
 {
  printf("Enter name, age and salary:\n");
  scanf("%s%d%d", w[i].name, &w[i].age, &w[i].salary);
  fwrite(&w[i], sizeof(w[i]), 1, p);
  printf("Stor another record? (yes or no):\n");
  scanf("%s", answer);
  i++;
 }while(strcmp(answer, "no") != 0);

 rewind(p);

 printf("Enter which record to display?\n");
 scanf("%d", &n);

 /* Reading records from file */
 for(i=0; i< n; i++)
 {
  fread(&w[i], sizeof(w[i]),1, p);
 }

 /* Displaying nth records */
 printf("Worker Name: %s\n", w[n-1].name);
 printf("Worker Age: %d\n", w[n-1].age);
 printf("Worker Salary: %d", w[n-1].salary);
 getch();
 return 0;
}