Nothing is done incorrectly - but you don't seem to understand what write to binary file does. It writes more or less the internal memory RAM representation of your data to disk.
EDIT: Perhaps you can tell us what you expected the file to look like...
Binary is only machine readable. Just write a program read it again using the appropriate tools and you get all your data back.
And don't use a *.txt extension, because it is not a text file!