C Program to sort structure of cars, file I/O

The information stored for an automobile at a car dealer are saved in the file cars.txt. Each line contains the record for a car including the make and model, manufacture year, city mpg, and highway mpg. Write a program that reads file cars.txt, store the data in an array of car structures, and sort the cars by average mpg (the average of city mpg and high way mpg). Output the sorted cars, including the average mpg in a text file called sorted_cars.txt.  A car structure should have the following attributes:

o make                         string

o model                        string

o manufacture year    int

o city mpg                   int

o highway mpg           int

You can assume the cars.txt as the following format for each car: make (one single word), model (one single word), manufacture year, city mpg, highway mpg.

Mercury Sable 2009 18 28 

Jeep Wrangler 2016 17 21


1. Name your program car.c.

2. The program should be built around an array of structures, with each structure containing information of a car’s make, model, manufacture  year, city mpg, highway mpg, and average mpg( average of the city mpg and highway mpg).  Assume the make and model are no more than 30 characters. Assume that there are no more than 1000 cars in the file.

3. Use fscanf and fprintf to read and write data.

4. Modify the selection_sort function provided to sort an array of product struct. The boxes should be sorted by average mpg in ascending order. The function should have the following prototype:

void selection_sort(struct car cars[], int n); 

5. Output the sorted cars, including average mpg, in a text file called sorted_cars.txt, in the following format.

Make        Model       year   city mpg    highway mpg  average mpg

Jeep         Wrangler  2016      17                      21                      19

Mercury   Sable        2009     18                      28                     23

Leave a Reply

Your email address will not be published. Required fields are marked *

  • File Format: C .c, Output file .txt
  • Lines of Code: 124