How to append a text file to another text file

74 views (last 30 days)
I have two files : file1.dat ans file2.dat and I want to add the content of the file2.dat to the end of file1.dat with a space between them like this :
How can I do this ?

Accepted Answer

Stephen23
Stephen23 on 2 Sep 2020
Edited: Stephen23 on 2 Sep 2020
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 Comments
Rafael Rodriguez
Rafael Rodriguez on 9 Mar 2022
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
Stephen23 on 9 Mar 2022
"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.

Sign in to comment.

More Answers (0)

Tags

Community Treasure Hunt

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

Start Hunting!