I won't do your homework for you, but I wrote a program that does similar things to what your program needs to do. Read the comments and try to understand the code. Then modify it to your needs.
The program reads from a file named "vgs.txt". This file contains video game names, sales, and ratings. My program formats this data and writes it to a file named "videogames.txt".
Here are the contents of vgs.txt:
skyrim 600 8.50420500
dark_souls 800 9.99999991
sonic 50 8.00123457
revelations 300 7.58493028
And videogames.txt is an initially empty file. Here is the code I wrote. I compiled it with:
gcc -ansi -pedantic -Wall -Werror -O0 -o VG vg.c
Code:
#include <stdio.h>
typedef struct _vg
{
char name[30]; /* Name of the video game */
int nsold; /* Number of copies sold */
float rating; /* Average rating out of 10 */
} VIDEOGAME;
int main(void) {
/* Declare variables */
FILE *fp1, *fp2;
VIDEOGAME vg;
int total_sold, ngames, error_check;
float total_avg;
char h1[30] = "Video Game",
h2[30] = "Units Sold",
h3[30] = "Rating";
/* Attempt to open file 1 for reading */
if( !(fp1 = fopen("vgs.txt", "r")) ) {
fprintf(stderr, "Could not open vgs.txt.\n");
return 1;
}
/* Attempt to open file 2 for writing */
if( !(fp2 = fopen("videogames.txt", "w")) ) {
fprintf(stderr, "Could not open videogames.txt.\n");
fclose(fp1);
return 1;
}
/* Print Headers */
fprintf(fp2, "%-30s\t%-30s\t%-30s\n\n", h1, h2, h3);
/* Initialize variables */
total_sold = 0;
total_avg = 0.0;
ngames = 0;
/* Loop until we are done reading file 1 */
while(!feof(fp1)) {
/* fscanf returns the number of tokens it managed to parse */
error_check = fscanf(fp1, "%s%d%f\n", vg.name, &vg.nsold, &vg.rating);
if(error_check != 3) {
fprintf(stderr, "Parsing error.\n");
fclose(fp1);
fclose(fp2);
return 1;
}
/* Print data to file 2 and update stats */
fprintf(fp2, "%-30s\t%-30d\t%-30.2f\n\n", vg.name, vg.nsold, vg.rating);
++ngames;
total_sold += vg.nsold;
total_avg += vg.rating;
}
/* Get the aggregated average */
total_avg /= ngames;
/* Print out total sales and aggregate average */
fprintf(fp2, "Total sales: %d\nAggregate Average: %.2f\n", total_sold, total_avg);
/* Clean up and exit */
fclose(fp1);
fclose(fp2);
return 0;
}
After running the code, here is the contents of "videogames.txt":
So, it doesn't do exactly what you need, but it does similar things. Try to understand it and you should be able to code your program just fine.