I am trying to read a struct from a binary file, but I have some problems. Here's the struct
struct note {
int id;
char str[20];
};
This is the code that writes to a binary file.
std::ofstream file("somefile.bin", std::ios::out | std::ios::binary);
if (file.is_open()) {
// some code to read input into the struct
file.write((char *) &mystruct, sizeof(mystruct));
}
file.close();
This works fine. But when I create another program to read from the binary file, I get some issues. The program compiles and it runs, but it doesn't read the file. Here's the code:
std::ifstream file("somefile.bin", std::ios::in | std::ios::binary)
// somefile is the file I created in the first program.
if (file.is_open()) {
while (!file.eof()) {
file.read((char *) &otherstruct, sizeof(otherstruct));
if (file.fail()) {
std::cout << "File read error!";
exit(1);
}
std::cout << "ID: " << otherstruct.id << "\nNote: " << otherstruct.str;
}
} else
std::cout << "File open error.";
file.close();
When I run the code I only get file read error. it means that this code executes.
if (file.fail()) {
std::cout << "File read error!";
exit(1);
}
Why isn't my code reading from the binary file?. Why is it failing to read the file?