Needed in C Write an auto parts store inventory program as follows. Define a str
ID: 3719038 • Letter: N
Question
Needed in C
Write an auto parts store inventory program as follows.
Define a structure type named “part” with the following variables in each structure:
Part number: an integer.
part name: a character array of 20 elements.
Cost: a float.
Quantity: an integer.
Create an array of twenty “part” structures.
Read the contents of the file “store” into the array.
Sort the structures in the array from least part name to highest part name (hint: use strcmp).
Display the values of the sorted array to the screen.
Calculate and output to the screen the total cost of all the part with the given quantities.
Ask the user for an output file name.
Write the array values in sorted order to the output file. Each output record has to be similar in format to input.
Submit the program file, input file, and output file in a zipped folder into the program 8 drop box.
The file containing the parts info is posted in the same module with the name “store.txt”.
store.txt
2535 brakepad 12.50 82
9892 fanbelt 22.35 36
4512 shiftcable 109.95 5
5152 waterpump 79.50 22
3265 fuelpump 115.30 34
9512 brakerotor 45.00 21
6935 battery 89.25 160
1436 wiperblades 5.85 220
Explanation / Answer
#include<stdio.h>
/*structure for parts */
typedef struct
{
int part_num;
char part_name[20];
float cost;
int quantity;
}part;
void main()
{
part arr[20],temp;
char output[20];
double sum=0;
int i,j;
FILE *fp1;
/* open store.txt file to read */
fp1 = fopen("store.txt","r");
/* See if file is opened successfully */
if(fp1 != NULL)
{
/* Read from file */
for(i=0;i<20;i++)
{
fscanf(fp1,"%d%s%f%d",&arr[i].part_num,arr[i].part_name,&arr[i].cost,&arr[i].quantity);
}
/* Sort from smallest to longest of part name */
for(i=0;i<20;i++)
{
for(j=0;j<20;j++)
{
if(strcmp(arr[i].part_name,arr[j].part_name)<0)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
/* display sorted list onto screen */
for(i=0;i<20;i++)
{
printf("%d %-15s %f %d ",arr[i].part_num,arr[i].part_name,arr[i].cost,arr[i].quantity);
}
/* Find and display total cost */
for(i=0;i<20;i++)
{
sum += arr[i].part_num*arr[i].cost;
}
printf("Total cost = %f ", sum);
fclose(fp1);
}
/* Display error if file is not opened */
else
{
printf("Error in opening file %s ","store.txt");
}
/* Accept output file name and write data into it */
printf("Enter the output file name: ");
scanf("%s",output);
fp1 = fopen(output,"w");
for(i=0;i<20;i++)
{
fprintf(fp1,"%d %s %f %d",arr[i].part_num,arr[i].part_name,arr[i].cost,arr[i].quantity);
fprintf(fp1," ");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.