如何在C语言中修改文本文件中指定ID对应的库存整数值?
解决文本文件中ID对应库存的更新问题
首先,咱们先聊聊你之前代码的问题:你用fscanf(filename, "%d", array[i])的时候,第一个参数传的是文件名,但fscanf需要的是打开后的文件指针(FILE*);另外,你直接把所有数字塞进一个数组,没法区分哪个是ID、哪个是对应库存——毕竟你的数据是成对出现的(ID+库存),这样处理会混淆两者的对应关系。
接下来给你一个完整的实现思路和代码示例,咱们用C语言来完成这个需求:
步骤1:定义数据结构存储ID和库存
用结构体来存储每一组ID和库存,这样能清晰对应两者的关系:
#include <stdio.h> #include <stdlib.h> // 定义存储ID和库存的结构体 typedef struct { int id; int stock; } Inventory;
步骤2:读取文件内容到结构体数组
先打开文件,然后成对读取ID和库存,存储到结构体数组里:
// 读取文件内容,返回存储的条目数,同时填充结构体数组 int read_inventory(const char* filename, Inventory** inv) { FILE* fp = fopen(filename, "r"); if (!fp) { perror("Failed to open file"); return -1; } int count = 0; int id, stock; // 先统计条目数量,方便分配内存 while (fscanf(fp, "%d %d", &id, &stock) == 2) { count++; } // 回到文件开头,准备读取数据 rewind(fp); // 分配内存存储所有条目 *inv = (Inventory*)malloc(count * sizeof(Inventory)); if (!*inv) { perror("Failed to allocate memory"); fclose(fp); return -1; } // 读取每一组ID和库存到结构体数组 for (int i = 0; i < count; i++) { fscanf(fp, "%d %d", &(*inv)[i].id, &(*inv)[i].stock); } fclose(fp); return count; }
步骤3:修改指定ID的库存
遍历结构体数组,找到目标ID后更新库存:
// 修改指定ID的库存,delta是变化量(正为增加,负为减少) int update_stock(Inventory* inv, int count, int target_id, int delta) { for (int i = 0; i < count; i++) { if (inv[i].id == target_id) { inv[i].stock += delta; printf("Updated ID %d: stock from %d to %d\n", target_id, inv[i].stock - delta, inv[i].stock); return 0; // 修改成功 } } printf("ID %d not found\n", target_id); return -1; // 未找到目标ID }
步骤4:将修改后的内容写回文件
把更新后的结构体数组重新写入文件:
// 将修改后的库存数据写回文件 int write_inventory(const char* filename, Inventory* inv, int count) { FILE* fp = fopen(filename, "w"); if (!fp) { perror("Failed to open file for writing"); return -1; } for (int i = 0; i < count; i++) { fprintf(fp, "%d %d ", inv[i].id, inv[i].stock); } // 可以在最后加个换行,让文件更规范 fprintf(fp, "\n"); fclose(fp); return 0; }
完整主函数示例
把上面的函数组合起来,实现给ID:106增加30库存的需求:
int main() { const char* filename = "inventory.txt"; Inventory* inv = NULL; int count = read_inventory(filename, &inv); if (count == -1) { return 1; } // 修改ID 106的库存,增加30 update_stock(inv, count, 106, 30); // 写回文件 if (write_inventory(filename, inv, count) == -1) { free(inv); return 1; } free(inv); return 0; }
额外说明
- 如果你不想用结构体,也可以用两个平行数组(一个存ID,一个存对应库存),但结构体的方式更清晰,不容易出错。
- 记得处理文件打开失败、内存分配失败的情况,这些错误处理能让程序更健壮。
- 如果你的文件很大,这种一次性读取到内存再修改的方式可能不太高效,但对于小型文本文件来说完全够用。
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

