Program 62) Write a program to open a file named INVENTORY and store in it the following data:
item name Number Price Quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
Extend the program to read this data from the file INVENTORY and display table with the value of each item.
This program shown below. The filename INVENTORY is supplied through the keyboard. Data is read using the function fscanf from the file stdin, which refers to the terminal and it is then written to the file that is being pointed to by the file pointer fp. Remember that the file pointer fp points to the file INVENTORY.
After closing the file INVENTORY, it is again reopened for reading. The data from the file, along with the item values are written to the file stdout, which refers to the screen. While reading from a file, care should be taken to use the same format soecifications with which the contents have been written to the file....e
PROGRAM
#include <stdio.h>
main ( )
{
FILE *fp ;
int number, quantity, i ;
float price, value ;
char item [10], filename [10] ;
printf ("Input file name\n") ;
scanf("%s", filename) ;
fp = fopen (filename, "w") ;
printf ("Item name Number Price Quantity\n") ;
for (i = 1; i <= 3; i++)
{
fscanf (stdin, "%s %d %f %d",
item, &number, &price, &Quantity) ;
fprintf (fp, "%s %d %.2f %d",
item, number, price, quantity) ;
}
fclose (fp) ;
fprintf (stdout, "\n\n") ;
fp = fopen (filename, "r") ;
printf ("Item name Number Price Quantity Value\n")
for (i = 1; i <=3; i++)
{
fscanf (fp, "%s %d %f d", item, &number, &price,
&quantity) ;
value = price * quantity ;
fprintf (stdout, "%-8s %7d %8.2f %8d %11.2f\n",
item, number, price, quantity, value) ;
}
fclose (fp) ;
}
Output: Input file name
INVENTORY
Input inventory data
Item name Number Price Quantity
AAA-1 111 17.50 115
BBB-2 125 36.00 75
C-3 247 31.75 104
Item name Number Price Quantity Value
AAA-1 111 17.50 115 2012.50
BBB-2 125 36.00 75 2700.00
C-3 247 31.75 104 3302.00
No comments:
Post a Comment