Each line of a textfile gradestxt contains the ID of a stude
Each line of a text-file grades.txt contains the ID of a student and his grades in 2 quizzes. Write a C program that reads grades.txt and writes to an output file output.txt the ID and the best quiz for each student.
Note: Your program must be general, it must work for any number of lines in the input file.
Sample input file grades.txt:
201100010 95.0 80.0
201100020 45.0 50.0
201100030 97.0 90.0
201100040 60.0 80.0
201100050 62.0 60.0
Sample output file output.txt:
ID BEST QUIZ SCORE
201100010 95.0
201100020 50.0
201100030 97.0
201100040 80.0
201100050 62.0
| 201100010 95.0 80.0 201100020 45.0 50.0 201100030 97.0 90.0 201100040 60.0 80.0 201100050 62.0 60.0 |
Solution
Please refer below code
#include<stdlib.h>
#include<stdio.h>
int main()
{
long int id;
float mark1,mark2;
FILE* fi = fopen(\"grades.txt\",\"rb\"); //open file in read mode
FILE* fp = fopen(\"output.txt\",\"wb\"); //ope file in write mode
if (fi == NULL)
{
printf(\"Could not open file \ \");
return 0;
}
fprintf(fp, \"ID \\t\\t\\t BEST QUIZE SCORE\ \");
while(fscanf(fi, \"%ld\\t%f\\t%f\", &id,&mark1,&mark2) > 0) //reading file line by line and storing each values in variables
{
//printf(\"Khushal %ld %f %f\", id,mark1,mark2);
if(mark1 > mark2) //writing data into file
fprintf(fp, \"%ld %.1f\ \", id, mark1);
else
fprintf(fp, \"%ld %.1f\ \", id, mark2);
}
printf(\"Please check output.txt for output\ \");
fclose(fi);
fclose(fp);
return 0;
}
grades.txt
201100010 95.0 80.0
201100020 45.0 50.0
201100030 97.0 90.0
201100040 60.0 80.0
201100050 62.0 60.0
output.txt
ID BEST QUIZE SCORE
201100010 95.0
201100020 50.0
201100030 97.0
201100040 80.0
201100050 62.0
here in grades.txt values are separated by tab
if the values in grades.txt is separated by space then just replace \\t with space in fscanf()

