-
write struct to file
hey im trying to store data in a file from a struct? can anyone point me to how i should go about doing this, i tried like this but it says that cant convert my struct to char *
Code:
struct user_data{
char username[25];
char password[25];
};
......
ofstream file(USER_DATA,ios::out|ios::binary);
file.write(ud,sizeof(ud));
file.close();
can someone please point me on how i should do this thanks.
-
u can do a memcpy to a character array.
-
Code:
file.write((char*)&ud, sizeof(ud));
Need to pass the address of the struct, not the struct itself.
Watch for structure padding when you write it (for example, it may write more than 50 bytes).
-
cheers, could i do the same if i wanted to read the file into a struct?
-
Code:
ifstream in(USER_DATA, ios::in | ios::binary);
in.read((char*)&ud, sizeof(ud));
in.close();
-
FYI:
If you look at the file with a text editor you can't read the text but
if you open it with a binary editor you can understand it.
You may want to look at encrypting the output if you don't want it
to easily be read.