-
Sorting from a file
heres code I have done so far, I am mostly confused on how to sort the array from the file and store the array.
Code:
/*
Algorithm:
1. In the main ( ), open the cars.dat file in the read mode and confirm
you have properly opened the file.
2. In the main ( ), read the entire contents of the cars.dat file into the
inventory array.
3. In the main ( ), close the cars.dat file
4. Call function_1( ), which will process the contents of the
inventory array by sorting the inventory array to place all the cars
in ascending order according to their price.
5. Call function_2( ), which will save (write) the sorted inventory
array to a file named output.dat
6. Terminate
ALGORITHM FOR function_1( ):
1.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct cars {
char make [ 20 ] ;
char model [ 20 ] ;
char color [ 15 ] ;
int year ;
double price ;
} cars ;
//Provide the prototype for your PCFs below:
void function_1(cars inventory[], int size);
int main (void)
{
//Local variables declared... add additional variables as required
cars inventory [ 25 ] ;
int size = 0;
FILE *input;
const char *inputfile = "cars.dat";
//1. Open the cars.dat file in the read mode and confirm
// you have properly opened the file.
input = fopen(inputfile, "r");
//2. Read the entire contents of the cars.dat file into the
// inventory array.
while ((fscanf(input, "%s%s%s%d%lf",
&inventory[size].make, &inventory[size].model,
&inventory[size].color, &inventory[size].year,
&inventory[size].price
) && (size < 25) ) size++;
//3. Close the cars.dat file
fclose(input);
//4. Call function_1( ), which will process the contents of the
// inventory array by sorting the inventory array to place all the cars
// in ascending order according to their price.
function_1(inventory, size);
//5. Call function_2( ), which will save (write) the sorted inventory
// array to a file named output.dat
//6. Terminate
return 0 ;
}
-
> and confirm // you have properly opened the file.
You don't do this step.
Code:
while ((fscanf(input, "%s%s%s%d%lf",
&inventory[size].make, &inventory[size].model,
&inventory[size].color, &inventory[size].year,
&inventory[size].price
) && (size < 25) ) size++;
You should check the size before doing the input, otherwise you will input over the non existent element 25 only to discover that shouldn't have.
Also, check the fscanf result is specifically 5.
Are you allowed to use this standard function?
qsort, qsort_s - cppreference.com
The essence of sorting is compare and swap.
Code:
if ( inventory[i].price > inventory[j].price ) {
cars temp = inventory[i];
inventory[i] = inventory[j];
inventory[j] = temp;
}
-
You should also turn up your compiler warnings, you have several errors with your code.
Before you worry about sorting the data you should insure that you have read the data correctly (print the array after the read).