Opening and writing to file using binary mode.

Hello.

Well, my problem is, I'm having a lot of trouble opening a file in binary mode.

Yes, I have looked for the answer to my problem, but come up short, now knowing how to use the information to my advantage, etc.

What I basically need, is the correct format for opening and writing to a file in binary mode.

Any help will be greatly appreciated.
You can use the file stream constructor: ofstream file ( "filename", ios::binary|ios::out );
Or the method 'open': http://www.cplusplus.com/reference/iostream/ofstream/open/
Well, I don't think it wrote the correct information to said file, when using the first method you suggested.

To be more specific, I am trying to write an encrypted message, which is encrypted in an XOR like way, to a text file. After the information was written, using your suggestion, I tried decrypting said information, but didn't get the correct result.

Any idea?

EDIT: Could using ofstream file (path.c_str(), iso::binary|ios::out ); be the problem?
Last edited on
did u decrypt it the right way?...
Yes, the decryption code works just fine.
Show the code that writes to the file.
This was it originally:
1
2
3
4
ofstream file;		
file.open (path.c_str());
file << note;
file.close();


Opening a file in binary mode is the only problem I'm having with my current project, so any help is greatly appreciated.
Last edited on
You are having the same problem g0dwin had:
http://www.cplusplus.com/forum/general/11272/

Good luck!
Duoas; do you think you could explain the code you posted in that reply?

I don't like using code, unless I understand it. :P
Well, after a bit of more testing, I found out that the @ character is causing the problems. When entering the @ character to be encrypted, and written to the text file, the encrypted value is corrupted.

Does anyone know how I could go about fixing this?
Open the file in binary mode and use the read() member function to read the binary data.
If you want to store a 2-byte word, you need to write it one byte at a time. In little-endian format, the low byte is first, then the high byte. So the value 0x1234 would be stored as

0x34
0x12

in the file. You must split the word up into bytes and write it one byte at a time:
1
2
3
short value = 0x1234;
f.put( (char)(  value       & 0xFF ) );
f.put( (char)( (value >> 8) & 0xFF ) );

To read the value again, you must do the opposite: read it one byte at a time and reassemble the value into a word:
1
2
3
4
short value;
value = f.get();
value <<= 8;
value |= f.get();



I think, however, my tiredness caused me to mis-diagnose your problem. When you do I/O, I imagine that you are doing it one character at a time. Use the istream::get() and ostream::put() methods instead of << and >>, and you shouldn't have any problems.

Good luck!
Topic archived. No new replies allowed.