Writing Cell array to File

8 ビュー (過去 30 日間)
Jason
Jason 2015 年 4 月 13 日
コメント済み: Jason 2015 年 4 月 13 日
I have a cell array of size:
ans =
2428 1
and an exmaple few lines are:
C1 =
'GA008246-0_B_F_1852967891'
'GA011810-0_B_F_1852968731'
'GA017861-0_B_F_1852970072'
'GA017864-0_T_R_1853027526'
I am trying tow rite to a file, and perform the following:
%Write to file:
fileID = fopen('c:\TestFile.txt','w');
fprintf(fileID,'i NOT A\n');
[nrows,ncols] = size(C1)
for row = 1:nrows
fprintf(fileID,'%s\n',C1{row,1});
end
fclose(fileID);
But the resultant text file appears not to include the new line, and each item in the list is just appended adjacent to the last one?

採用された回答

Guillaume
Guillaume 2015 年 4 月 13 日
It's very unfortunate that matlab's own examples don't include the 't' in their fopen call when dealing with text files, as it is indeed very important.
It assume your test was on Windows and that you used Notepad to look at the text file. The problem then occured because notepad only recognises the 'Windows' line ending (\r\n) and ignores 'Unix' line ending (just \n). Some more powerful editors would have shown you a line return.
Using 't' in fopen tells matlab to automatically translate the line endings so that they are right for the platform you are writing / reading the file on. On windows it writes \r\n for you if you only specify \n.
  1 件のコメント
Jason
Jason 2015 年 4 月 13 日
Thats a great explanation, thankyou. Jason

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2015 年 4 月 13 日
編集済み: Jan 2015 年 4 月 13 日
I cannot confirm your observations. Please try it again with a folder you have write access to:
C1 = {'GA008246-0_B_F_1852967891'; ...
'GA011810-0_B_F_1852968731'; ...
'GA017861-0_B_F_1852970072'; ...
'GA017864-0_T_R_1853027526'};
fileID = fopen(fullfile(tempdir, 'TestFile.txt'), 'w'));
if fileID == -1
error('Cannot open the file');
end
fprintf(fileID,'i NOT A\n');
for row = 1:numel(C1)
fprintf(fileID, '%s\n', C1{row});
end
fclose(fileID);
  1 件のコメント
Jason
Jason 2015 年 4 月 13 日
I now works when I use the following (include the t in the file permissions).
fileID = fopen('c:\TestFile.txt','wt');

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLow-Level File I/O についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by