c语言写一个商品信息储存和读取模块
时间: 2023-05-14 12:06:23 浏览: 52
可以使用结构体来储存商品信息,使用文件来进行储存和读取。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 50
#define MAX_DESC_LEN 100
typedef struct {
int id;
char name[MAX_NAME_LEN];
char desc[MAX_DESC_LEN];
float price;
} Product;
void save_product(Product *p) {
FILE *fp = fopen("products.dat", "ab");
if (fp == NULL) {
printf("Failed to open file!\n");
exit(1);
}
fwrite(p, sizeof(Product), 1, fp);
fclose(fp);
}
void load_products() {
FILE *fp = fopen("products.dat", "rb");
if (fp == NULL) {
printf("Failed to open file!\n");
exit(1);
}
Product p;
while (fread(&p, sizeof(Product), 1, fp) == 1) {
printf("ID: %d\n", p.id);
printf("Name: %s\n", p.name);
printf("Description: %s\n", p.desc);
printf("Price: %.2f\n", p.price);
printf("\n");
}
fclose(fp);
}
int main() {
Product p1 = {1, "Product 1", "This is product 1", 10.0};
Product p2 = {2, "Product 2", "This is product 2", 20.0};
save_product(&p1);
save_product(&p2);
load_products();
return 0;
}
```
这个程序定义了一个 Product 结构体,包含商品的 ID、名称、描述和价格。save_product 函数将一个 Product 结构体写入文件,load_products 函数从文件中读取所有 Product 结构体并打印出来。在 main 函数中,我们创建了两个 Product 结构体并保存到文件中,然后读取并打印所有 Product 结构体。