How to make new lines in binary files

Hi all,

Yes I know that .txt files are also binary files but the question is how do I create a newline, when writing to a "binary" file?

eg: When I open a file like this ofstream myfile("jee.bin",ios::app);, and I want to print text into the file in different lines like this:

How do I do it?

Looked for several methods, but they ALL failed me,
Just print and endl or '\n'
IceThatJaw wrote:
Just print and endl or '\n

Yeah thanks for replying. I tried that but it also did not work.
This is how I did it: myFile<<endl;

Also, I think it has got something to do with the write() function associated with files opened in binary mode.

You wouldn't be writing to a 'binary' file here, since you opened it in text mode.

You seem to be asking, "what sequence of bytes does my system use to end lines in text mode?" Hard to say since we don't know what system you're using. Easy enough for you to figure out for yourself though. All it requires is opening a text file in binary mode created on your system with a linebreak in it and reading in the byte sequence used to indicate the linebreak. That same sequence is what you would write in binary mode to end a line as you would in text mode.
Thank you all for your suggestions.

Also, in
ofstream myfile("jee.bin",ios::app);
, I forgot the ios::binary flag. Typos...

All the best,
Last edited on
If you are using Windows, you may need to send the CR-LF sequence "\r\n", as that is what most programs expect as a line separator.
Last edited on

Thank you soo much! It works.

Topic archived. No new replies allowed.