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
}
CodePudding user response:
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:
Close the
std::ofstream
, which flushes all unwritten data to the actual file, orexplicitly 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:
Use a single
std::fstream
, which handles both reading and writing, and then properly useflush()
, andseekg()
, to reposition the file stream for reading, orClose the output file first, then open the same file for reading, after it is closed for writing.