How to append a text file to another text file
8 次查看(过去 30 天)
显示 更早的评论
采纳的回答
Stephen23
2020-9-2
编辑:Stephen23
2020-9-2
Assuming no trailing newline characters in the files, perhaps one of these:
Append to existing file:
st2 = fileread('file2.dat');
[fid,msg] = fopen('file1.dat','at');
assert(fid>=3,msg)
fprintf(fid,'\n\n%s',st2);
fclose(fid);
Create a new file:
st1 = fileread('file1.dat');
st2 = fileread('file2.dat');
[fid,msg] = fopen('newfile.dat','wt');
assert(fid>=3,msg)
fprintf(fid,'%s\n\n%s',st1,st2);
fclose(fid);
5 个评论
Rafael Rodriguez
2022-3-9
What if I have a text file with multiple "trailing new line characters". I just want to append it to the end of another file. This could be a simple copy/paste outside of matlab, but I want to include it in my script.
The file is on the order of 100 lines long, so it would take a lot of "fprintf" with specific formatting for each line.
thanks!
Stephen23
2022-3-9
"The file is on the order of 100 lines long, so it would take a lot of "fprintf" with specific formatting for each line."
I don't see why: FILEREAD includes all newline characters in its output, so you can simply use one FPRINTF call to print file content together with all of its newline characters. Even if that were not the case (e.g. you imported each line separately into a cell array, sans newline characters) it would still be trivial using just one FPRINTF call (and including the newline in the format string).
So far nothing you have explained requires more than one FPRINTF call.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
