You just need to submit the C source file. Do not submit the input file or the o
ID: 3844359 • Letter: Y
Question
You just need to submit the C source file. Do not submit the input file or the output file. Check your program carefully before submission. Test data differs from the sample input will be used in the grading. Make sure your program works properly for all possible cases. File in. txt stores the information for multiple students including ID, name and score of math and physics. The first line of in.txt indicates the number of students. Your program need to read the content of in, calculate the sum of students' score and write students' ID, name and total score to the file out.txt. The students in out.txt should be in the order defined as follows. You need to use qsort function in header file stdlib.h to sort the students. Do not write your own code for sorting. The student with greater total grade will rank first. If two students have the same total grade, the student with less student ID will rank first. Students' IDs will always be unique. Dynamic structure array allocation and deallocation is required. Sample Input & Output The content of in.txt is 4 105 Tom 76 74 103 Jim 67 88 101 Lucy 72 78 185 Sam 57 67 The content of out.txt is 103 Jim 155 101 Lucy 150 105 Tom 150 185 Sam 124Explanation / Answer
C Program:
/* c Program that reads student data from one file and write to another file */
#include <stdio.h>
#include <stdlib.h>
//Student structure
struct Student
{
int id;
char name[10];
int totalScore;
};
//Function that works with qsort
int compare (const struct Student * a, const struct Student * b)
{
return b->totalScore - a->totalScore;
}
//Main function
int main()
{
int totalStudents;
//Array of structures
struct Student **students;
int i, id, score1, score2, totalScore;
char name[10];
//File pointer
FILE *fp, *outfile;
//Opening files
fp = fopen("in.txt", "r");
outfile = fopen("out.txt", "w");
//Reading number of students
fscanf(fp, "%d", &totalStudents);
//Allocating memory
students = (struct Student*)malloc(totalStudents * sizeof(struct Student));
//Reading student data
for(i=0; i<totalStudents; i++)
{
fscanf(fp, "%d %s %d %d", &id, name, &score1, &score2);
//Allocating memory
students[i] = (struct Student*)malloc(sizeof(struct Student));
//Assigning data
students[i]->id = id;
strcpy(students[i]->name, name);
students[i]->totalScore = score1 + score2;
}
//Sorting student data
qsort (students, totalStudents, sizeof(struct Student*), compare);
//Writing to file
for(i=0; i<totalStudents; i++)
{
fprintf(outfile, " %d %s %d ", students[i]->id, students[i]->name, students[i]->totalScore);
}
//Closing files
fclose(fp);
fclose(outfile);
//Deallocating memory
free(students);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.