I'm now learning file i/o and I'm very confused about one part of it.
When it comes to binary, you should use 2 parameters in the read/write method: the first one to specify a pointer to the first byte of the variable, the second one to specify the amount of bytes of the variable.
I understand it up to this part. What I'm confused with, is the first parameter. There are a few examples given in the tutorial I'm following:
(char*)array
(char*)&object
(char*)object
When do you need to use a reference and when not? I don't see any logic in it. Can someone please explain this?
First of all, never read/write objects (structs/classes). Some might argue it's okay to read/write POD structs, but since the exact layout is subject to compiler tweaks, this makes it impossible to know for sure exactly how the file format is layed out (there might be additional padding where you didn't expect, or variables might be moved around or something. Plus if the struct/class contains a complex object that CAN'T be read/written directly (like a string), you're hosed. You're betting off writing member functions for the struct/class which read/write each of its members individually.
Anyway to read/write, you simply supply a pointer to the start of whatever it is you're writing:
1 2 3 4 5
int singleval = 5;
myfile.write( (char*) &singleval, sizeof(singleval) );
int array[6] = {1,2,3,4,5,6};
myfile.write( (char*) array, sizeof(array) );
Remember that an array name without its [brakets] gives you a pointer to the array, so you wouldn't do &array because array by itself is already a pointer. Alternatively you could do &array[0].
I would also go so far as to say don't write anything greater than a byte. If you've got multibyte values, separate them manually into bytes and reconstitute them when reading. Also, don't read/write floating point values in binary format unless they are in IEEE standard format or the documentation for your file format explicitly indicates otherwise -- else just write them as character string data.
I'm now letting the user inputting a file path and the program needs to open it.
The file path is saved as a string, which is used as the parameter in the open method. It didn't work and I've found out the c_str() method needs to be used. It works fine now.
My question is: why does it needs to be converted to a c-string?