Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C program in terminal/linux machine: Assume each line of a csv file has three it

ID: 3726258 • Letter: C

Question

C program in terminal/linux machine:

Assume each line of a csv file has three items: name,age,GPA. You can assume the name is at most 50 characters, the age is a whole number with at most 3 digits, and the GPA has at most 2 digits after the decimal point (for example, 3.17). Also, you can assume that there are no more than 100 lines in the csv file. Your program must:

Take a csv filename as a command line argument.

Open the csv file and use fgets to read the contents.

Store the data in an array of structures.

Write the data out to a new csv file called output.csv, with the following changes:

In each line, switch the positions of the age and GPA data.

Reverse the order of the lines.

Add a line at the end with the average GPA and average age in the 2nd and 3rd fields.

Other than the changes above, the data in the output file should be identical to the data in the input file (exact same characters with no change in formatting or numerical approximations).

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct details{
   char name[50];
   int age;
   float gpa;
}stu[100];
int main(int argc, char **argv){
   FILE *fp,*op;
   char s[60];
   char *token;
   int k = 0,i;
   double avg_age = 0, avg_gpa = 0;
   if ((fp= fopen(argv[1], "r")) == NULL) {
        printf("cannot open file");
        exit(1);
   }
   op = fopen("output.csv","w");
   fgets(s, 60, fp);
   while(!feof(fp)) {
        token = strtok(s, ",");
        strcpy(stu[k].name,token);
       token = strtok(NULL, ",");
       stu[k].age = (int) atoi(token);
       token = strtok(NULL, ",");
       stu[k].gpa = (float) atof(token);
       k++;
        fgets(s, 60, fp);
    }
    for(i=k-1;i>=0;i--){
        avg_age += stu[i].age;
        avg_gpa += stu[i].gpa;
        fprintf(op, "%s,%.2f,%d ", stu[i].name, stu[i].gpa, stu[i].age);
    }
    avg_gpa /= k;
    avg_age /= k;
    fprintf(op, "%s,%.2f,%.2f ", "", avg_gpa, avg_age);
    fclose(fp);
   return 0;
}

input:

output:

bharat 20 8.42 shanavaz 20 8.3 karthik 21 8.5 ravi 25 7.5