0

I'm trying to append new lines to a .txt file in a loop with MATLAB as follows:

for i=1:N
    % do something
    % something done. write them to text file:
    fid = fopen(outfile, 'a');
    for j = 1:numel(smth.text)
        fprintf(fid, '\n%s;%d', smth.text{j}, smth.data(j));
    end
    fclose(fid);
end

when I'm finished, I open the file in Notepad++ (if relevant, the encoding is UTF-8) and see it correctly, i.e.:

text1;data1
text2;data2
etc

however, when I open the file in Windows' Notepad, I see it like this:

text1;data1text2;data2etc

so the line breaks are not showing up in Notepad.

How can I fix this so I can get the newlines everywhere?

Thanks for any help,

jeff
  • 13,055
  • 29
  • 78
  • 136
  • See also: [Why does fprintf behave differently in text mode compared to a properly set carriage return in normal mode?](http://stackoverflow.com/questions/19298269/why-does-fprintf-behave-differently-in-text-mode-compared-to-a-properly-set-carr/) – sco1 May 13 '16 at 14:03
  • See also: [fprintf not printing new line](http://stackoverflow.com/questions/6536599/fprintf-not-printing-new-line) – sco1 May 13 '16 at 14:04

1 Answers1

1

You need to add \r in yoru fprintf command for windows Notepad to identify the line break (notepad++ display will not be affected).

for i=1:N
  % do something
  fid = fopen(outfile, 'a');
  for j = 1:numel(smth)
    fprintf(fid, '\r\n%s;%d', smth.text{j}, smth.data(j));
  end
  fclose(fid);
end

A good explanation for the difference between \r and \n can be found here

Community
  • 1
  • 1
matlabgui
  • 5,642
  • 1
  • 12
  • 15
  • Thanks for your quick answer. However it's not working as expected; Notepad display is not changed (still no breaks), and in Notepad++ I get double breaks instead of single ones. **Edit**: when I change the order, i.e. make it `\r\n`, it works! Is this what you meant? – jeff May 13 '16 at 12:03
  • Yes - I wrote the answer from memory without testing so I put them the wrong way - I will update – matlabgui May 13 '16 at 12:10