You're welcome. :)
File:
1010Borvandoin1001010
|
Close, but not quite. What you've written here is 1's and 0's in plain text, defeating the purpose of using raw binary representation at all. Every "character" in a file takes one full byte of data. So your textual "1010" is going to consume 4 bytes -- ASCII values 49, 48, 49, 48. Take a look at this chart to see what I'm talking about, and ignore everything except the "Chr" and "Dec" columns:
http://www.asciitable.com/
This is what I am proposing, given the example name/length you've provided:
Byte 1 of file: 10, to signify the length of the name. Just 10 (in decimal, of course). The value of the BYTE (single "character") is ten. We don't care if that looks like anything textually -- incidentally, it represents a line-feed, but like I said, we don't care what it would mean in a file that was pure human-readable text, we just care that we stored a value of 10 in that byte. You are correct in that its binary representation is 1010, but the point is that we stored it in a single byte.
Byte 2 of file: 66, representing 'B'.
Byte 3 of file: 111, representing 'o'.
Byte 2 of file: 114, representing 'r'. (this part, you wrote correctly, I just wanted to point out what is happening behind the scenes)
And so on.
To flesh this out into some code, let's say we're saving a file, we know that the user's name is Borvandoin, and its length is 10, so we want to write a byte value of 10 and then the text itself to the file. We would do something like (I'm not actively testing this, so can't guarantee if I have the syntax perfect):
1 2 3
|
ofstream outfile ("save.dat");
outfile.put (10);
outfile.write (string_containing_name, 10);
|
Thus we first write a *single byte value* of 10 for the first byte, then follow it up with the 10 bytes containing the name. Then when the time comes along that the user wants to load, and we want to read it back in, we do something like:
1 2 3 4
|
ifstream infile ("save.dat");
char name_length;
infile.get (name_length);
infile.read (string_for_name, name_length);
|
Making any sense yet? Don't feel bad if it takes a bit of time, this isn't easy stuff and I find myself hoping I didn't go overboard with my suggestion. But do you see how clean the method is once you know how to do it?