ofstream problems

Started by
4 comments, last by reaper101 22 years, 8 months ago
Hi all! Here''s a interesting question... Why is it that the following code outputs 13 and 10: void WriteFile(char *newfile) { ofstream fout(newfile, ios::out); fout.put((char)10); fout.close(); } It should only output 10! What''s going on? It''s probably just a simple mistake. Any help would be greatly appreciated! reaper
Advertisement
You're in Windows, and you're writing in text mode (rather than binary mode). Character '10' is 'newline'. Newlines in text mode are converted to carriage returns + new lines under Windows when writing to a file. Carriage return is 13, which is why you're seeing 13 then 10. Changing to binary mode should fix it. (PS. The ios::out is the default for ofstreams, so you don't need to specify it.)

Edited by - Kylotan on August 2, 2001 9:19:25 PM
i had this problem a while back too. it has something to do with opening the file in ios::binary mode. in standard mode ASCII 10 and 13 are line feed and carriage return...basically the same thing, and it treats them as such. the simplest thing to do is treat the stream as a binary stream, not a character stream. otherwise, avoid using those characters. hope that helps.

cyn
Something to note is that some stream functions are formatted, and others are not. Formatted functions (like put()) will do a conversion for some characters when the stream is opened in text mode, like you have seen in your code. However, they won''t do any conversion in binary mode. On the other hand, unformatted functions will not do any conversion, even if the stream is in text mode.

put() and operator<< are formatted. I think that there is a function called write() that is unformatted. You can check the MSDN for others.
"It tastes like burning..."
Thank you guys sooo much! It works great! I was really having quite a time of it! :-) Thanks for such a quick responses! Hope I can be of some help in the future.

reaper
Thank you guys sooo much! It works great! I was really having quite a time of it! :-) Thanks for such a quick responses! Hope I can be of some help in the future.

reaper

This topic is closed to new replies.

Advertisement