Skip to main content

INVENTORY file of items

Short answer

Open INVENTORY in write mode; while user enters 'y' and count<10000, read item name, number, price, quantity, write with fprintf. Reopen for reading, read with fscanf until EOF, display table with value = price × quantity.

Write a program to open file named INVENTORY and store in it for maximum 10000 data of ITEM_NAME, NUMBER, PRICE, QUANTITY. Extend the program to read this data from the above given filename and display the inventory table with the value of each item.

Design. Each item has ITEM_NAME, NUMBER, PRICE and QUANTITY. The program asks for items one by one (a maximum of 10000, tested with count < MAXITEMS) and writes each to the file INVENTORY with fprintf(). The file is then closed and opened again for reading; fscanf() reads item by item until it stops returning 4. A table is shown, with value = price × quantity for every item.

#include <stdio.h>
#define MAXITEMS 10000

int main(void)
{
    FILE *fp;
    char name[30], more = 'y';
    int number, qty, count = 0;
    float price;

    fp = fopen("INVENTORY", "w");
    if (fp == NULL) {
        printf("Cannot open INVENTORY\n");
        return 1;
    }
    while (more == 'y' && count < MAXITEMS) {
        printf("Item name, number, price, quantity: ");
        scanf("%29s %d %f %d", name, &number, &price, &qty);
        fprintf(fp, "%s %d %.2f %d\n", name, number, price, qty);
        count++;
        printf("More items (y/n)? ");
        scanf(" %c", &more);
    }
    fclose(fp);

    fp = fopen("INVENTORY", "r");
    if (fp == NULL) {
        printf("Cannot open INVENTORY\n");
        return 1;
    }
    printf("\n%-12s %-8s %-10s %-8s %s\n", "ITEM_NAME", "NUMBER", "PRICE", "QUANTITY", "VALUE");
    while (fscanf(fp, "%29s %d %f %d", name, &number, &price, &qty) == 4)
        printf("%-12s %-8d %-10.2f %-8d %.2f\n", name, number, price, qty, price * qty);
    fclose(fp);
    return 0;
}

Sample run

Input (entered one after another): Pen 101 10.50 100 y Notebook 102 45 60 y Bag 103 1200 5 n

ITEM_NAME    NUMBER   PRICE      QUANTITY VALUE
Pen          101      10.50      100      1050.00
Notebook     102      45.00      60       2700.00
Bag          103      1200.00    5        6000.00

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 10 questions →