简体   繁体   中英

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

I am using the below code to read and write to struct using the ifstream and ofstream classes. But for some reason I am not able to read back from the file.

#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));

This will place the indicates bytes to std::ofstream 's internal buffer , rather than the actual file. Like all efficient input/output frameworks, iostreams -- both input and output -- uses an internal buffer to efficiently read and write large chunks of data. When writing, all written data is collected in the internal buffer until there's enough to write the entire buffer to the file. Your small structure falls far short of being large enough to actually write anything to the file.

You should either:

  1. Close the std::ofstream , which flushes all unwritten data to the actual file, or

  2. explicitly call flush() .

Additionally, the shown code opens the same file both for reading and writing, simultaneously:

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

Even if the output is properly flushed, first, depending on your operating system it may not be possible to simultaneously have the same file open for reading and writing. You should either:

  1. Use a single std::fstream , which handles both reading and writing, and then properly use flush() , and seekg() , to reposition the file stream for reading, or

  2. Close the output file first, then open the same file for reading, after it is closed for writing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM