it outputs on the txt file |
Which is it? ;P binary or text?
Anyway... to really understand what binary files are and how they work, you should probably get a hex editor. I recommend HxD, as it's probably the best free Hex Editor I've ever used.
It's available here:
http://mh-nexus.de/en/hxd/
I ran your program on my machine... input
filename = out.bin
record number = 0
name = name
age = 16
Here's what the resulting file looks like in a hex editor:
http://imgur.com/XTRcZco
The highlighted section is the "age", whereas the rest (black text only) is the "name"
Note what you're doing here:
fbin.write(name, sizeof(name)-1);
sizeof(name) is going to be 20 because that's how big the array is. You then subtract 1 from that... so you're writing 19 bytes from the 'name' array to the buffer.
And if you look at the file in a hex editor... that's exactly what happened. The first 19 bytes in the file are "name", followed by the null terminator (value of 00), followed by a bunch of random garbage that was left uninitialized in the 'name' buffer.
You then do this:
fbin.write((char*)(&age), sizeof(int));
sizeof(int) is 4 on my machine. So this wrote 4 bytes (the highlighted section)
Since the age was 16... in hex.. in 4 bytes that would be 0x00000010
Stored little endian (low byte first), that's 10 00 00 00 ... which is exactly what's in the file.
If you open this in a text editor like notepad... you'll see something similar to what's in the right column there. 'name' followed by a bunch of garbage symbols (look kind of like Is). That's because text editors read the file... and interpret each byte as being the ascii code for a character.
So yeah. Use text editors for text files.
Use hex editor for binary files.