In C language: (text files provided) Description: This function should open and
ID: 3825360 • Letter: I
Question
In C language: (text files provided)
Description: This function should open and read the given input file which contains information about all rental cars.
It should store each car's data in an element of the given array arr, and return the number of cars it read from the file.
Notice that the file contains extra information which you should just skip/ignore (using * option in fscanf)
Obviously the value of member is_available should be initialized to 1 for all elements of array arr.
Function:
int readCarsInfo(char *filename, CarInfo arr[]) {
int n = 0;
// ...
return n;
}
Seperate text file, cars.txt:
Car ID Car Make Car Model Year Unit Price Per Day MPG
----------------------------------------------------------------------------------------------------------------------------------------------------------
311 Chevrolet Chevelle-Malibu 1 2014 45.99 21
312 Buick Skylark-320 2014 79.95 19
313 Plymouth Satellite 2017 61.75 N/A
314 AMC Rebel-SST 2016 99.99 16
315 Ford Torino 2015 85.99 22.1
316 Ford Galaxie-500 2016 61.95 29.5
317 Chevrolet Impala 2013 42.99 18.7
318 Plymouth Fury-iii 2017 69.85 20.52
319 Pontiac Catalina 2012 29.99 N/A
320 AMC Ambassador-DPL 2015 95.99 16.30
321 Citroen DS-21-Pallas 2016 59.75 19.05
In a seperate struct.h:
typedef struct {
unsigned int ID; //unique identification number of the car
char model[20];
char make[20];
unsigned int year;
float unit_price; //rental cost per day for this car
int is_available; //whether the car is already rented or not (0 if it's rented, 1 otherwise)
} CarInfo;
Explanation / Answer
int readCarsInfo(char *filename, CarInfo arr[]) {
int n = 0;
//CarInfo carinfo[20];
FILE* file = fopen (filename, "r");
if(file == NULL)
return 1;
int count = 0;
while (!feof (file))
{
unsigned int ID; //unique identification number of the car
char model[20];
char make[20];
unsigned int year;
float unit_price; //rental cost per day for this car
int is_available;
fscanf (file, "%d %s %s %d %f %d %*[^ ] ", &ID,model,make,&year,&unit_price ,NULL);
printf( "%d %s %s %d %f %d *", ID,model,make,year,unit_price );
arr->ID=ID;
strcpy(arr->model,model);
strcpy(arr->make,make);
arr->year=year;
arr->unit_price=unit_price;
arr->is_available = is_available;
n++;
}
fclose (file);
return n;
}