使用c语言写一串代码实现商品库存管理系统,要求用到文本文件
时间: 2024-04-03 18:34:13 浏览: 51
C语言实现库存管理系统
好的,以下是一个简单的商品库存管理系统的C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ITEMS 100 // 最大商品数量
#define MAX_NAME_LEN 50 // 商品名称最大长度
typedef struct {
int id;
char name[MAX_NAME_LEN];
int quantity;
} Item;
int read_items(Item items[]) {
FILE *fp;
fp = fopen("items.txt", "r");
if (fp == NULL) {
printf("Failed to open items.txt\n");
return 0;
}
int i = 0;
while (!feof(fp) && i < MAX_ITEMS) {
int id, quantity;
char name[MAX_NAME_LEN];
fscanf(fp, "%d %s %d", &id, name, &quantity);
items[i].id = id;
strcpy(items[i].name, name);
items[i].quantity = quantity;
i++;
}
fclose(fp);
return i;
}
void write_items(Item items[], int num_items) {
FILE *fp;
fp = fopen("items.txt", "w");
if (fp == NULL) {
printf("Failed to open items.txt\n");
return;
}
for (int i = 0; i < num_items; i++) {
fprintf(fp, "%d %s %d\n", items[i].id, items[i].name, items[i].quantity);
}
fclose(fp);
}
void print_items(Item items[], int num_items) {
printf("ID\tName\tQuantity\n");
for (int i = 0; i < num_items; i++) {
printf("%d\t%s\t%d\n", items[i].id, items[i].name, items[i].quantity);
}
}
int main() {
Item items[MAX_ITEMS];
int num_items = read_items(items);
while (1) {
printf("1. Add item\n");
printf("2. Remove item\n");
printf("3. Update quantity\n");
printf("4. Print items\n");
printf("5. Exit\n");
printf("Enter your choice: ");
int choice;
scanf("%d", &choice);
switch (choice) {
case 1: {
if (num_items == MAX_ITEMS) {
printf("Maximum number of items reached\n");
} else {
Item item;
printf("Enter item ID: ");
scanf("%d", &item.id);
printf("Enter item name: ");
scanf("%s", item.name);
printf("Enter item quantity: ");
scanf("%d", &item.quantity);
items[num_items] = item;
num_items++;
write_items(items, num_items);
printf("Item added successfully\n");
}
break;
}
case 2: {
int id;
printf("Enter item ID to remove: ");
scanf("%d", &id);
int found = 0;
for (int i = 0; i < num_items; i++) {
if (items[i].id == id) {
for (int j = i; j < num_items - 1; j++) {
items[j] = items[j + 1];
}
num_items--;
write_items(items, num_items);
printf("Item removed successfully\n");
found = 1;
break;
}
}
if (!found) {
printf("Item not found\n");
}
break;
}
case 3: {
int id, quantity;
printf("Enter item ID to update quantity: ");
scanf("%d", &id);
int found = 0;
for (int i = 0; i < num_items; i++) {
if (items[i].id == id) {
printf("Enter new quantity: ");
scanf("%d", &quantity);
items[i].quantity = quantity;
write_items(items, num_items);
printf("Quantity updated successfully\n");
found = 1;
break;
}
}
if (!found) {
printf("Item not found\n");
}
break;
}
case 4: {
print_items(items, num_items);
break;
}
case 5: {
printf("Exiting...\n");
return 0;
}
default: {
printf("Invalid choice\n");
break;
}
}
}
return 0;
}
```
这个程序使用了一个`Item`结构体来存储每个商品的ID、名称和数量。它从文本文件`items.txt`中读取商品信息,并在修改后将其写回文件。可以通过菜单实现添加、删除、更新和打印商品的功能。
阅读全文