Merge two text files using uiget

1 view (last 30 days)
Avi Dutt-Mazumder
Avi Dutt-Mazumder on 3 Jan 2019
Answered: Akira Agata on 4 Jan 2019
I have three text files in a directory called Open1.txt Open2.txt Open3.txt
I want to use a uiget to choose any two text files,
then merge those two files
and finally export the merged file as a text file.
My first part of the code is working but unable to merge the chosen two files and exporting them as a one text file. My snipet code is below
m=0;
while m<3
m=menu('Options','load data','combine file','save file');
if m==1 % Load .txt data
[file, path] = uigetfile('*.Open*.txt',...
'Select One or More Files', ...
'MultiSelect', 'on');
if isequal(file,0)
disp('User selected Cancel');
else
disp(['User selected ', fullfile(path,file)]);
end
filepath=fullfile('path','file');
fid = fopen('filepath');
cd(path);
dfilename=(['C:\Users\Folder\',file]);
end
if m==2 %Combine multiple txt files
  3 Comments
Luna
Luna on 3 Jan 2019
You should be doing: (I didn't understand how it works btw)
fid = fopen(filepath);
% below is wrong syntax
fid = fopen('filepath');
Avi Dutt-Mazumder
Avi Dutt-Mazumder on 3 Jan 2019
I manged it, while thinking over it
The later part of the code is
if m==2 %Combine multiple files
Ofilestr='CombinedFile.txt'; % open an empty file to merge all
fid = fopen(Ofilestr,'w');
fclose(fid);
for n = 1:numel(file)
system(['type ' file{n} ' >> ' Ofilestr]);
end
end

Sign in to comment.

Answers (1)

Akira Agata
Akira Agata on 4 Jan 2019
One possible solution would be like this.
Just FYI:
  • Since menu function is not recommended in recent MATLAB versions, I have replaced it with questdlg function.
  • I have removed 'combine file' option because the following code combines just after loading txt file when 'load data' was selected.
answer = 'load data';
txtData = cell(0);
while strcmp(answer,'load data')
% Show the selection button
answer = questdlg('What would you like to do?', ...
'Options', ...
'load data','save file','load data');
if strcmp(answer,'load data')
% Load data and combine
[file, path, idx] = uigetfile('*.txt',...
'Select One or More Files', ...
'MultiSelect', 'off');
if ~idx
h = errordlg('User selected Cancel');
uiwait(h);
else
fid = fopen(fullfile(path,file));
c = textscan(fid,'%s','Delimiter','\n');
txtData = [txtData; c{1}];%#ok
fclose(fid);
end
else
% Save the combined data as txt file
[file2,path2] = uiputfile('*.txt');
writetable(table(txtData),fullfile(path2,file2),...
'WriteVariableNames',false);
end
end

Community Treasure Hunt

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

Start Hunting!