Q. Write a program to input 10 employee records (Emp_id, Emp_Name and Emp_Salary) and store them in a data file named "Emp.dat". Display the employee information who gets highest salary.
#BIT_FirstSem_2015_1No_12Marks_Solution
Code goes like this:
#include<stdio.h>
int main()
{
FILE *fptr;
fptr=fopen("D:\\Emp.dat","w+");
/* if(fptr=NULL)
{
printf("File cannot be created");
exit(1);
} */
struct employee
{
int emp_id;
char emp_name[20];
float emp_salary;
};
struct employee emp[10],temp;
int i,j,n;
float tempforsalary;
printf("How many records: ");
scanf("%d",&n);
for ( i = 0; i < n; i++)
{
printf("Emp id: ");
scanf("%d",&emp[i].emp_id);
printf("Emp Name: ");
scanf("%s",emp[i].emp_name);
printf("Salary: ");
scanf("%f",&tempforsalary);
emp[i].emp_salary=tempforsalary;
fflush(stdin);
fprintf(fptr,"\n Emp id\t Name \t Salary\n");
fprintf(fptr,"\n %d\t %s\t %.2f\n ",emp[i].emp_id,emp[i].emp_name,emp[i].emp_salary);
printf("\n");
}
fclose(fptr);
//Highest Salary
for ( i = 0; i < n-1; i++)
{
for ( j = i+1; j < n; j++)
{
if(emp[i].emp_salary<emp[j].emp_salary)
{
temp=emp[i];
emp[i]=emp[j];
emp[j]=temp;
}
}
}
//Printing highest Salary
printf("Employee having highest salary: \n");
printf("Emp Id: %d\t Name: %s\t Salary: %.2f",emp[0].emp_id,emp[0].emp_name,emp[0].emp_salary);
return 0;
}
Output:
If we see in D: we can find Emp.dat file having following content:
If you are using Turbo C++ IDE, then use conio.h in link section after stdio.h
and use getch(); to hold the output screen, just before the end of main function.
If you have any confusion regarding the program, please, comment below.
Happy Coding !
Thank you
Displaying employee info having highest salary from data file having 10 records - C
5:49 PM
C Programs
,
Data files in c
,
file handling
,
finding highest salary
,
OldQuestionSolution2015C
,
structure
Edit
0 comments:
Post a Comment