fprintf中的char函数matlab:写入文件时保留新行

时间:2017-05-30 07:47:53

标签: matlab char fopen

我正在尝试将Equip函数的输出传递给Item,以便我可以将多行写入文本文件。问题是char()忽略了行之间的所有空格,而是打印了一条大行。我想要打印fprintf,而不会丢失新行。

fprintf(fid,'%s\n', str)

原始数据/文本文件内容,作为字符串的单元格数组读入变量str

str = (char(textlinepre));
filename = 'newfile.dat';
fid = fopen(filename,'w');
fprintf(fid,'%s\n', str);    
fclose(fid);

2 个答案:

答案 0 :(得分:1)

获取字符串的单元格数组(在您的情况下,您可以从外部文件中获取此字符串)

textlinepre = {'line1', 'line2', 'line3'};

写入文件

filename = 'newfile.dat';
fid = fopen(filename,'w');
% Print to file line by line, so '\n' is added after every element
for ii = 1:numel(textlinepre)
    fprintf(fid, '%s\n', textlinepre{ii}); 
end
fclose(fid);

以下是完成此操作的数学示例:Export cell array to text file

答案 1 :(得分:0)

构建textlinepre的方式一定有问题。我有下面的代码,它工作正常

textlinepre = sprintf(['%% leafspring1\n' ...
                       'BEAM 1 1 2 3 4 0.0000000000 1.0000000000 0.0000000000\n'...
                       '%% solid bar\n'...
                       'BEAM 2 3 4 5 6 0.0000000000 0.0000000000 1.0000000000\n'...
                       '%% leafspring2\n'...
                       'BEAM 3 5 6 7 8 0.0000000000 1.0000000000 0.0000000000\n\n'...
                       'X 1 0.0000000000 0.0000000000 0.0000000000']);
str = (char(textlinepre));

filename = 'newfile.dat';
fid = fopen(filename,'w');
fprintf(fid,'%s\n', str); 
fclose(fid);