仅使用 C++ 无法从具有整数类型的结构读取和写入

reading and writing from structs with integer types only with c++ not working

我正在使用以下代码通过 ifstream 和 ofstream 类 读取和写入结构。但出于某种原因,我无法从文件中读回。

#pragma pack(1)
struct test {
    int m_id;
    int m_size; //changed to integer
    test(int id, int size) :m_id(id), m_size(size) {}
    test() {};

};
#include <climits>
int main() {
    ifstream in;
    ofstream out;
    out.open("binFile", ios::binary | ios::out);
    in.open("binFile", ios::in | ios::binary);
    test old(1, 7);
    out.write(reinterpret_cast<char*>(&old), sizeof(old));    
    test new(10,100);
    in.read(reinterpret_cast<char*>(&new), sizeof(new));
    cout << new.m_size; //diplays 100 
    
}
out.write(reinterpret_cast<char*>(&s1), sizeof(s1));

这会将指示字节放入 std::ofstream 内部缓冲区 ,而不是实际文件。与所有高效的 input/output 框架一样,iostreams(包括输入和输出)使用 an internal buffer 来高效地读取和写入大块数据。写入时,所有写入的数据都收集在内部缓冲区中,直到有足够的数据将整个缓冲区写入文件。您的小型结构远远不够大,无法实际向文件写入任何内容。

您应该:

  1. 关闭 std::ofstream,这会将所有未写入的数据刷新到实际文件,或者

  2. 明确地call flush().

此外,显示的代码同时打开同一个文件进行读写:

out.open("binFile", ios::binary | ios::out);
in.open("binFile", ios::in | ios::binary);

即使输出被正确刷新,首先,根据您的操作系统,可能无法同时打开同一个文件进行读写。您应该:

  1. 使用单个 std::fstream,它同时处理读取和写入,然后正确使用 flush()seekg() 来重新定位文件流以供读取, 或

  2. 先关闭输出文件,然后打开同一个文件进行读取,之后关闭写入.