You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在同一.dat文件中保存并读取整数与结构体数组?

嘿,我看到你已经在着手实现二进制文件的读写逻辑了——要把计数器作为.dat文件的第一个数据,接着存储结构体数组对吧?我来帮你补全代码,还要提几个关键注意点,确保你的读写逻辑能正常跑起来!

完善后的写入函数

先帮你补全并优化你写的写入逻辑,这里默认你的结构体是常见的库存项格式,你可以根据自己的实际定义替换:

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

// 示例结构体定义(请根据你的实际需求修改)
typedef struct {
    int itemId;
    char itemName[50];
    float price;
    int quantity;
} InventoryItemType;

void write(InventoryItemType writefile[], int count) {
    // 注意:你原代码的参数是指针数组,这里改成直接传结构体数组更合理
    int i;
    FILE *ptr;
    ptr = fopen("inventory.dat", "wb");
    if (ptr == NULL) {
        printf("Unable to Open File\n");
        system("pause");
        return;
    }

    // 写入计数器作为文件首个内容
    if (putw(count, ptr) == EOF) {
        printf("Failed to write item count to file\n");
        fclose(ptr);
        system("pause");
        return;
    }

    // 循环写入结构体数组
    for (i = 0; i < count; i++) {
        size_t written = fwrite(&writefile[i], sizeof(InventoryItemType), 1, ptr);
        if (written != 1) {
            printf("Failed to write item %d to file\n", i);
            fclose(ptr);
            system("pause");
            return;
        }
    }

    printf("Successfully saved %d inventory items\n", count);
    fclose(ptr); // 务必关闭文件,避免资源泄漏
}
对应的读取函数

既然要保存,肯定也需要读取逻辑,这里给你配套实现:

int read(InventoryItemType **readfile) {
    // 返回读取到的计数器值,通过二级指针返回结构体数组
    int count;
    FILE *ptr;
    ptr = fopen("inventory.dat", "rb");
    if (ptr == NULL) {
        printf("Unable to Open File\n");
        system("pause");
        return -1; // 返回-1标记读取失败
    }

    // 读取文件首个整数(计数器)
    count = getw(ptr);
    if (count == EOF) {
        printf("Failed to read item count or file is empty\n");
        fclose(ptr);
        system("pause");
        return -1;
    }

    // 为结构体数组分配内存
    *readfile = (InventoryItemType *)malloc(count * sizeof(InventoryItemType));
    if (*readfile == NULL) {
        printf("Memory allocation failed\n");
        fclose(ptr);
        system("pause");
        return -1;
    }

    // 循环读取结构体数据
    for (int i = 0; i < count; i++) {
        size_t read = fread(&(*readfile)[i], sizeof(InventoryItemType), 1, ptr);
        if (read != 1) {
            printf("Failed to read item %d from file\n", i);
            free(*readfile); // 出错时释放已分配内存,避免泄漏
            fclose(ptr);
            system("pause");
            return -1;
        }
    }

    printf("Successfully loaded %d inventory items\n", count);
    fclose(ptr);
    return count;
}
关键注意事项
  • 结构体一致性:读写时的结构体定义必须完全一致,包括成员顺序、类型、大小,否则会出现读取乱码或数据错误。
  • 二进制模式:必须用wb(写入二进制)和rb(读取二进制)模式,绝对不能用文本模式(w/r),否则换行符转换会破坏二进制数据。
  • 文件关闭:每次操作完文件一定要调用fclose(),否则可能导致数据未及时写入磁盘或资源泄漏。
  • 错误处理:代码里加了putw/fwrite/fread的返回值检查,实际开发中这些检查能帮你快速定位问题。
  • 内存管理:读取时用malloc分配的内存,使用完毕后一定要记得调用free()释放,避免内存泄漏。

内容的提问来源于stack exchange,提问作者Trial'n'Error

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:30:24