How to append a text file to another text file

72 Ansichten (letzte 30 Tage)
Izem
Izem am 2 Sep. 2020
Kommentiert: Stephen23 am 9 Mär. 2022
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 ?

Akzeptierte Antwort

Stephen23
Stephen23 am 2 Sep. 2020
Bearbeitet: Stephen23 am 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 Kommentare
Rafael Rodriguez
Rafael Rodriguez am 9 Mär. 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 am 9 Mär. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Low-Level File I/O finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by