Reputation: 491
While compiling this simple code:
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
class Example
{
public:
char charo;
int into;
};
int main()
{
Example one,two;
one.charo = 'X'; one.into = 2;
//WRITING
ofstream file;
file.open("my.prx", ios_base::binary);
if(file.good()) file.write((char*)&one, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//READING
file.open("my.prx", ios_base::binary);
if(file.good())
file.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
file.close();
//PRINTING
cout << "CHAR: " << two.charo << endl;
cout << "INT: " << two.into << endl;
}
I get this error message:
g++ -o test1 main.c main.c: In function ‘int main()’: main.c:43:7: error: ‘std::ofstream’ has no member named ‘read’
file.read((char*)&two, sizeof(Example));
How can I solve it? My next step will be to make a more complicated object to save:
Class Memory{
t_monitor monitors[MAX_MONITORS];
t_status status[MAX_STATUS];
t_observer observers[MAX_OBSERVERS];
Var * first_var;
int tot_observers;
int tot_status;
int tot_monitors;
};
As you can see there is also a list...
Upvotes: 3
Views: 363
Reputation: 1844
Use ifstream
to read ostream
is used for output.
You can do something like this
std::ifstream fileRead( "my.prx",std::ifstream::binary );
if(fileRead)
fileRead.read((char*)&two, sizeof(Example));
else cout << "ERROR WHILE OPENING FILE" << endl;
fileRead.close();
Upvotes: 1
Reputation: 12897
An [ofstream][1]
is output only. One readable way is to use the variables ofstream ofile
and ifstream ifile
. This way the usage is clear from the declaration and the name. If the code grows, this might be helpful.
Another way would be to use the dual-use fstream
, but this can make certain operations ambiguous.
Of course, these days, you're probably better off using some sort of serialization library. First, preferring the one that your company or group already uses, and then, if that one is inadequate, picking a modern lib like Boost or, my fave, Cereal.
Upvotes: 1
Reputation: 46323
ofstream
is an output file stream. It's used for output, and can't "read".
Use fstream
instead.
Upvotes: 2