MATLAB: How to append a text file to another text file

text file

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 ?

Best Answer

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);