write linebreaks into text file

  • Follow


I want to write linebreaks into a text file:

fid = fopen('wgcodedef.tex','wt');
text = 'first line\n second line';
fprintf(fid,'%s',text);
fclose(fid);

I however get only a single line with 'first line\n second line'
which is not what I want.

How should this be done correct?
0
Reply Matthias 12/11/2010 3:06:00 PM

> fid = fopen('wgcodedef.tex','wt');
> text = 'first line\n second line';
> fprintf(fid,'%s',text);
> fclose(fid);

Do instead of just text, use sprintf(text):

fprintf(fid, '%s', sprintf(text));

Let us know if you don't understand why '\n' in Matlab is treated as a two-element vector instead of a string literal, which is why we have to use sprintf.
0
Reply Ahmed 12/11/2010 3:47:05 PM


On 11/12/10 9:06 AM, Matthias Pospiech wrote:
> I want to write linebreaks into a text file:
>
> fid = fopen('wgcodedef.tex','wt');
> text = 'first line\n second line';
> fprintf(fid,'%s',text);
> fclose(fid);
>
> I however get only a single line with 'first line\n second line'
> which is not what I want.
>
> How should this be done correct?

\n is only special within formats, not within character strings.

You could _try_ using char(10) in its place, but I am not sure that 
would work properly on Windows to provide both the carriage return and 
line feed; e.g.,

text = ['first line' char(10) ' second line'];

Proper approaches: use fwrite() putting in the exact bytes needed for 
your system, or break up the output line by line and use '%s\n' format.

Alternative suggestion:

text = {'first line' ' second line'};
fprintf(fid, '%s\n', text{:});
0
Reply Walter 12/11/2010 3:58:23 PM

On 11/12/10 9:47 AM, Ahmed Fasih wrote:
>> fid = fopen('wgcodedef.tex','wt');
>> text = 'first line\n second line';
>> fprintf(fid,'%s',text);
>> fclose(fid);
>
> Do instead of just text, use sprintf(text):
>
> fprintf(fid, '%s', sprintf(text));
>
> Let us know if you don't understand why '\n' in Matlab is treated as a
> two-element vector instead of a string literal, which is why we have to
> use sprintf.

Ahmed, that will not work if the text might contain any special 
formatting characters such as 'first line\n second line\n 100% complete'

If one is completely certain that \n is the only special formatting 
character, then that technique is redundant, replaceable by just
fprintf(fid, text);


I have always been cautious about sprintf() and Windows text files: 
sprintf() does not know it is intended for a text file and so is going 
to emit char(10) for \n in the string, but will fprintf() expand that 
char(10) in to carriage return and line feed even when that char(10) 
occurs in the text to be printed rather than in the format string ?
0
Reply Walter 12/11/2010 4:32:56 PM

3 Replies
408 Views

(page loaded in 0.076 seconds)

Similiar Articles:













7/13/2012 4:12:21 PM


Reply: