\n Not Generating New Line In fprintf fid Command When Writing To .dat File

2 views (last 30 days)
I have a loop going and am trying to write output each time to a .dat text file appending it every iteration; but not getting a new line.
for minute = 18:1:48
thetaL = 15*(hour+minute/60+second/3600);
h = thetaL-alpha;
a = asin(sin(phi0)*sin(beta)+cos(phi0)*cos(beta)*cos(h));
A = atan((sin(h))/(cos(h)*sin(phi0)-tan(beta)*cos(phi0)));
fid = fopen('astro_conv_table.dat', 'a');
fprintf(fid, '%.0f %s %.0f %s %.0f %.0f %.0f
\n',hour,':',minute,':',second,a,A);
fclose(fid);
end
Everything in the code is working fine except the output is written to file in one long line as opposed to intended new line every iteration.
Thank you.

Accepted Answer

José-Luis
José-Luis on 4 Oct 2012
Edited: José-Luis on 4 Oct 2012
I assume you are in Windows. The return of carriage for Windows is "\r\n". Try changing that. Otherwise, use wordpad instead of notepad. Or get any decent text editor, like notepad++, which is free.
  4 Comments
Jan
Jan on 4 Oct 2012
Even on Windows machines "\n" is a newline. Only the "Editor" of Windows does not understand this correctly. I do not know any other software, which does not accept the CHAR(10) as line break properly.
Matlab's LOAD does not recognize the CHAR(13) line break when reading a file in ASCII format, but this has been used by old Apple software until OS-9 only.

Sign in to comment.

More Answers (1)

Stephen23
Stephen23 on 12 Jan 2018
The simplest solution by far is to fopen the file in text mode, simply by using the t option. This mode converts all newlines to \n when reading, and when writing converts \n to the appropriate type for your OS.
For the original question, all that is required is adding the t to fopen:
fid = fopen('astro_conv_table.dat', 'at'); % note the "t" !
fprintf(fid, '%.0f %s %.0f %s %.0f %.0f %.0f\n',hour,':',minute,':',second,a,A);
fclose(fid);
and it will insert the correct Windows newline characters.
  1 Comment
Jan
Jan on 12 Jan 2018
While opening in text mode is simple, it is also simple to stay at char(10) on all machines and avoid to use the Windows Notepad. I prefer the 2nd way of simplicity, most of all if I want to discuss with a Linux or Mac user.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!