Saving multiple .txt files into one .txt file

6 views (last 30 days)
Hi,
I am running a code that gives out 3 text files with different answers, i need to add the 3 text files into 1 big text file how can i do this in order, i have used a code that was able to take the 3 files and add them into one but the answers got a mixed up and they were in random order.

Answers (1)

Geoff Hayes
Geoff Hayes on 15 Apr 2020
Austin - you may want to show the code that you had to combine the three files and we can perhaps discuss why it didn't work. Else, if I want to concatenate text files together, I might use the Unix cat command as
system('cat filename1 filename2 filename3 > newfilename')
where the actual filenames are included (the filename1, filename2, etc. are just examples - you would need to include your filenames and perhaps the path to each file). If running on Windows, you can use copy to merge the files together.
  2 Comments
Geoff Hayes
Geoff Hayes on 19 Apr 2020
Edited: Geoff Hayes on 19 Apr 2020
Austin's answer moved here
Hi Geoff - apologies here is the code below -
files=dir('*.txt');
fileout='output.txt';
fout=fopen(fileout,'w+');
for cntfiles=1:length(files)
fin=fopen(files(cntfiles).name);
temp = fread(fin,'uint8');
fwrite(fout,temp,'uint8');
fprintf(fout,'\n');
fclose(fin);
end
fclose(fout);
i have almost fixed the code the only problem i have is that the code is printing the same text files twice in the same file, any idea on how to fix this?
Geoff Hayes
Geoff Hayes on 19 Apr 2020
Austin - do you mean that if you run the same code a second time, then the same text is included in the file? This could be because your filter is picking up the file "output.txt" and so you need to ignore it. Try
files=dir('*.txt');
fileout='output.txt';
fout=fopen(fileout,'w');
for cntfiles=1:length(files)
if strcmp(files(cntfiles).name, fileout) ~= 1
fin=fopen(files(cntfiles).name);
temp = fread(fin,'uint8');
fwrite(fout,temp,'uint8');
fprintf(fout,'\n');
fclose(fin);
end
end
fclose(fout);

Sign in to comment.

Categories

Find more on Entering Commands in Help Center and File Exchange

Tags

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!