MATLAB Answers

How to append a text file to another text file

11 views (last 30 days)
Izem
Izem on 2 Sep 2020
Commented: Izem on 2 Sep 2020
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 ?

  0 Comments

Sign in to comment.

Accepted Answer

Stephen Cobeldick
Stephen Cobeldick on 2 Sep 2020
Edited: Stephen Cobeldick 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);

  3 Comments

Izem
Izem on 2 Sep 2020
Thank you so much! It worked. What is te utility of this line 'assert(fid>=3,msg)'?
Stephen Cobeldick
Stephen Cobeldick on 2 Sep 2020
" What is te utility of this line 'assert(fid>=3,msg)'?"
Gives more detailed information (the second output from fopen) in the event that a file cannot be opened, otherwise you will just get a message telling you that the file ID is not valid. The message tells you why.

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!