Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C programming Write a program that will open a data file containing inventory in

ID: 3891332 • Letter: C

Question

C programming

Write a program that will open a data file containing inventory information and print a formatted report from the data.

1) Get the name of the data file from the user, then print a message about opening the data file and try to open that file for reading. If the file could not be opened, then print an error message. Close the file at the end of the main() function.

Note - the data file that will work with this lab is named data.txt (1 pt)

Ex: Enter file name: myfile.txt Opening data file... Could not open file myfile.txt

2) After opening the file, print column headings for the report - "ITEM", "QUANTITY", and "PRICE". The first two column headings should be left aligned in a field width of 10, and the third column heading should be right aligned in field with of 6. Print a double-underline for the column headings using the same column widths. (1 pt)

Enter file name:

data.txt

Opening data file...

ITEM QUANTITY PRICE

==== ======== =====

3) While you are not at the end of the file, read a line of data into an input string (up to 256 characters). Use fgets() to read your string. Then parse the input string into an item (a string), a quantity (an int), and a price (a double). Print the item, quantity, and price using formatted output as follows: (3 pts)

Item should be left aligned with a minimum field width of 10 and a maximum field width of 10 Print 4 spaces Quantity should be printed with a field width of 2 Print 6 spaces Price should be printed with a field width of 6 and 2 decimal places

NOTE: The data file that will be used in the test cases is called data.txt, and contains the following data:

Chair 16 59.95 Table 3 115 Rug 23 85.5 Lamp 12 39.9 Sofabed-large 4 999.95 Sofa-small 6 475.25

Explanation / Answer

Program

#include<stdio.h>
struct sales{
char item[20];
int quantity;
float price;
}s[6];

int main()
{

char filename[100];
FILE *fp;
char ch;
int i;

// Prompt user to enter filename
printf("Enter a filename :");
gets(filename);
   fp = fopen(filename,"r");

   if (fp!=NULL)

{
    printf(" Opening data file... ");
    printf(" ITEM QUANTITY PRICE");
    printf(" ==== ======== =====");
    for(i=0;i<6;i++)
{
    fscanf( fp, "%[^    ]s,%d,%f", s[i].item,&s[i].quantity,&s[i].price);
    printf(" %-10s %-10d %6f",s[i].item,s[i].quantity,s[i].price);
}
}
else
    {
printf("Could not open file data.txt");
}
fclose(fp);

}