fwrite() :如何编写嵌套结构

fwrite() : how to write nested structs

我在 C++ 中定义了以下结构

// This is the record
typedef struct {
    unsigned int recid;
    unsigned int num;
    char str[STR_LENGTH];
    bool valid;  // if set, then this record is valid
} rec;

// This is the definition of a block, which contains a number of fixed-sized records
typedef struct {
    unsigned int blockid;
    unsigned int nreserved; // how many reserved entries
    rec entries[MAX_RECORDS_PER_BLOCK]; // array of records
    bool valid;  // if set, then this block is valid
} blk;

数据处理后,我想将其写入文件。 fwrite() 是要走的路。我有一个功能:

void WriteValidRecords(FILE *outfile, blk *buffer) {
    for (uint i = 0; i < buffer->nreserved; i++) {
        if (buffer->entries[i].valid) {
            // I think here is the mistake!!
            fwrite(&(buffer->entries[i]), 1, sizeof(rec), outfile);
        }
    }
}

将记录 1 1 1 写入文件。这可以编译,但我在文件中得到的是错误的。我认为我在 fwrite() 作为第一个参数传递的指针是问题所在。但是我已经尝试了很多东西,但我似乎无法找到放在那里的东西。

我不确定这是否重要,但我就是这样称呼 WriteValidRecords():

blk *buffer = new blk[nmem_blocks];

temp = fopen(("temp", "wb");

// Do stuff

for (uint i = 0; i < nmem_blocks; i++) {
    WriteValidRecords(temp, &buffer[i], nios);
}

编辑:

temp以二进制形式打开。

我也在linux,是的..

编辑 2:

好的,我尝试在读写模式下打开文件,我认为这应该打印它读取的内容。它不是。它一次又一次地打印同样的东西。

void WriteValidRecords(FILE *outfile, blk *buffer) {
    for (uint i = 0; i < buffer->nreserved; i++) {
        if (buffer->entries[i].valid) {
            fwrite(&(buffer->entries[i]), 1, sizeof(rec), outfile);
            fseek(outfile, -sizeof(rec), SEEK_CUR);
            rec tmp;
            fread(&tmp, 1, sizeof(rec), outfile);
            cout << tmp.recid << endl;
            cout << tmp.num << endl;
            cout << tmp.str << endl;
        }
    }
}

根据您提供给我们的信息并假设您完全按照描述使用代码,我猜您的问题是 fopen() 以只写模式编辑文件。如果您不关闭文件并以适当的模式再次重新打开它(即 fopen(filename, "rb")fread 实际上不会读取任何内容。在上面的代码中,如果您检查 return 值fread,你会看到它是零。

将打开模式更改为 "w+b" 或以适当的访问模式重新打开文件以读回数据。