5

I am trying to send an array that is [2 x N] doubles large to a text file using the fprintf() command. I am having problems in that fprintf() is not recognizing the new line command (\n) or the carriage return command (\r). The code I am using is

fid = fopen([Image.Dir,'CtlPts_',Image.Files{k},'.txt'],'w');
fprintf(fid,'%.4f\t%.4f\n',control_points{k});
fclose(fid);

where the data I am trying to print is in the cell control_points{k}.

The tab gets printed fine, but everything in the text file gets printed on one line, so this is why I am assuming that it is ignoring my new line character.

Is there something wrong with my syntax that I am not seeing?

Amro
  • 123,847
  • 25
  • 243
  • 454
thron of three
  • 521
  • 2
  • 6
  • 19
  • 2
    have you done a dump of the file? I know that on many systems, \n is not enough to create what you're asking for (and so, maybe you have to do \r\n) – KevinDTimm Jun 30 '11 at 14:49
  • @KevinDTimm I am not sure what doing a dump of a file is (could you explain in an answer format) but using \r\n worked. Post this as an answer and I will select it. – thron of three Jun 30 '11 at 15:03
  • the reason for the dump is to verify that the file actually contains the \n. If it does (which is likely) then the second part of my comment / answer applies. – KevinDTimm Jun 30 '11 at 15:15
  • For others who come here: it often is because the number of `FormatString` specifiers (the `%--` bits in the line you're printing) are more than the number of numbers you give it to print. In such cases, newlines don't print. – jvriesem Oct 13 '17 at 03:46

2 Answers2

10

I know that on many systems, \n is not enough to create what you're asking for (and so, maybe you have to do \r\n)

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
9

An alternative solution is to open the file in text mode, that way MATLAB automatically inserts a carriage return \r before any newline \n character in the output on Windows systems:

fid = fopen('file.txt', 'wt');
fprintf(fid, '%f\t%f\n', rand(10,2));
fclose(fid);

Note that this is somewhat unnecessary, since most editors (with the exception of Microsoft Notepad) recognize Unix/Mac/Windows line endings.

Amro
  • 123,847
  • 25
  • 243
  • 454