In: Computer Science
Summary
Three employees in a company are up for a special pay increase. You are given a file, say Ch3_Ex5Data.txt, with the following data:
Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1
Each input line consists of an employee’s last name, first name, current salary, and percent pay increase.
For example, in the first input line, the last name of the employee is Miller, the first name is Andrew, the current salary is 65789.87, and the pay increase is 5%.
Instructions
Write a program that reads data from a file specified by the user at runtime (i.e. your program should accept the filename as user input) and stores the output in the file Ch3_Ex5Output.dat. To test your program, use the Ch3_Ex5Data.txt file.
Your program will not pass all checks if it does not accept a filename as input from the user.
For each employee, the data must be output in the following form: firstName- (Adam) lastName- (Zeb) updatedSalary.
Format the output of decimal numbers to two decimal places.
Since your program handles currency, make sure to use a data type that can store decimals.
C code for above problem
#include<stdio.h>
// function that returns the number of lines in given file
int get_length(char name[])
{
int len=0;
char line[100];
FILE *fp=fopen(name,"r");
while(fgets(line,sizeof(line),fp))
{
len++;
}
fclose(fp);
return len;
}
// tetsing main function
int main()
{
char name[100];
printf("Enter the file name: ");
scanf("%s",name);
FILE *fin=fopen(name,"r");
if(fin==NULL)
{
printf("File not found\n");
return 0;
}
FILE *fout=fopen("output.txt","w");
int len=get_length(name);
for(int i=0;i<len;i++)
{
char fname[50],lname[50];
float amount,percent;
fscanf(fin,"%s %s %f
%f",lname,fname,&amount,&percent);
amount+=(percent/100)*amount;
fprintf(fout,"%s - (Adam) %s -
(Zeb) %.2f\n",fname,lname,amount);
}
fclose(fin);
fclose(fout);
return 0;
}
Sample output
if "Ch3_Ex5Data.txt" has following data
Miller Andrew 65789.87 5
Green Sheila 75892.56 6
Sethi Amit 74900.50 6.1
then after running the above code, "output.txt" looks as follows:
Andrew - (Adam) Miller - (Zeb) 69079.36
Sheila - (Adam) Green - (Zeb) 80446.12
Amit - (Adam) Sethi - (Zeb) 79469.43
Mention in comments if any mistakes or errors are found. Thank you.