产品入库操作系统

编写一个简单的产品入库操作系统是一个涉及文件操作、用户输入和数据处理的项目。以下是一个基本的C语言示例,它展示了如何创建一个简单的产品入库系统。这个系统将允许用户添加产品信息,并将其存储在文件中。

功能描述

  1. 添加产品信息(产品ID、名称、数量)。
  2. 将产品信息保存到文件中。
  3. 从文件中读取并显示所有产品信息。

示例代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int id;
    char name[100];
    int quantity;
} Product;

void addProduct(Product *product) {
    printf("Enter Product ID: ");
    scanf("%d", &product->id);
    printf("Enter Product Name: ");
    scanf("%s", product->name);
    printf("Enter Product Quantity: ");
    scanf("%d", &product->quantity);
}

void saveProducts(const char *filename, Product *products, int count) {
    FILE *file = fopen(filename, "w");
    if (file == NULL) {
        perror("Error opening file");
        return;
    }
    for (int i = 0; i < count; i++) {
        fprintf(file, "%d %s %d\n", products[i].id, products[i].name, products[i].quantity);
    }
    fclose(file);
}

void loadProducts(const char *filename, Product *products, int *count) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file");
        return;
    }
    while (fscanf(file, "%d %99s %d\n", &products[*count].id, products[*count].name, &products[*count].quantity) != EOF) {
        (*count)++;
    }
    fclose(file);
}

void displayProducts(Product *products, int count) {
    printf("Product Inventory:\n");
    for (int i = 0; i < count; i++) {
        printf("ID: %d, Name: %s, Quantity: %d\n", products[i].id, products[i].name, products[i].quantity);
    }
}

int main() {
    char choice;
    Product products[100];
    int count = 0;
    const char *filename = "products.txt";

    do {
        printf("1. Add Product\n");
        printf("2. Display Products\n");
        printf("3. Exit\n");
        printf("Enter choice: ");
        scanf(" %c", &choice);

        switch (choice) {
            case '1':
                addProduct(&products[count]);
                saveProducts(filename, products, count + 1);
                count++;
                break;
            case '2':
                loadProducts(filename, products, &count);
                displayProducts(products, count);
                break;
            case '3':
                printf("Exiting program.\n");
                break;
            default:
                printf("Invalid choice. Please try again.\n");
        }
    } while (choice != '3');

    return 0;
}

说明

  1. 数据结构:使用了一个结构体Product来存储产品信息。
  2. 添加产品addProduct函数用于获取用户输入的产品信息。
  3. 保存产品saveProducts函数将产品信息保存到文件中。
  4. 加载产品loadProducts函数从文件中读取产品信息。
  5. 显示产品displayProducts函数用于显示所有产品信息。
  6. 主循环main函数中的循环允许用户选择不同的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值