How to append a text file to another text file

76 visualizaciones (últimos 30 días)
Izem
Izem el 2 de Sept. de 2020
Comentada: Stephen23 el 9 de Mzo. de 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 ?

Respuesta aceptada

Stephen23
Stephen23 el 2 de Sept. de 2020
Editada: Stephen23 el 2 de Sept. de 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 comentarios
Rafael Rodriguez
Rafael Rodriguez el 9 de Mzo. de 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 el 9 de Mzo. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Low-Level File I/O en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by