Doh! Adding Carriage return to fwrite Text file

Started by
5 comments, last by Vanz 20 years, 11 months ago
Hi all, I''m creating a small text file for documenting variables and can''t remember for the life of me how to add a carriage return to the text file so that I can read it clearer. I using code based on the following:

stream = fopen( FName, "wb" );

fwrite( "Sentence1", sizeof( char ), 9, stream );
fwrite( "Sentence2", sizeof( char ), 9, stream );
fwrite( "Sentence3", sizeof( char ), 9, stream );

fclose(stream);
 
Right now this would create a text file like this: Sentence1Sentence2Sentence3 I want it oo look like: Sentence1 Sentence2 Sentence3 tried adding "\\r", "\r", "\n", doesn''t seem to work. Thanks rhuala
Advertisement
I believe in windows, new-lines are signaled by the character 13 followed by character 10. (or the other way around). You can write it in binary though, in which case all you need is a ''\n''.


''I never let schoolling get in the way of my education'' - Samuel Clemens, a.k.a. Mark Twain

Check out my raytracer at http://www.sourceforge.net/projects/simp-raytracer. Download it at http://simp-raytracer.sourceforge.net.
If you are writing text to a file, you want to use formatted output functions like fprintf. fwrite is raw binary output, and much more difficult to use for text. Using the latter under Windows, to break to the next line you have to use a carriage return-line feed pair (a.k.a CRLF), which would be "\r\n". On UNIX machines it''s just "\n".
If you are creating a text file, shouldn''t you be opening the file in text mode?
Maybe your problem is that you open your file with "wb", which means that you create a binary file for writing.

Try to open you file with "w" and your file will be considered as a text file.
Good point about the wb thing, but Zipster''s post got it working for me, so thanks. Just added the \r\n and now it comes out all perdi and I can paste into a spreadsheet and disect it now, like reading the fricken matrix screen

Thanks again

rhuala

"The wb thing" - opening your file in binary rather than text mode - is the cause of your problem. When files are opened in text mode, the stdio routines (including fwrite) will automatically translate the native form of newlines (which will be different depending on platform) to and from "\n" for you. By instead writing "\r\n" in binary you are explicitly creating Windows textfiles (with CRLF newlines).

[edited by - spock on May 5, 2003 7:40:44 PM]

This topic is closed to new replies.

Advertisement