How to ask user before overwriting a text file?
11 views (last 30 days)
Show older comments
Hi, I want to write some data from MATLAB to a text file. But I want if the text file existed, ask the user if they want to overwrite the text file. Any suggestion?
Thanks
P.S. I'm writing the text files using:
fileID = fopen('Test.txt','w');
fprintf(fileID,'Hello!');
0 Comments
Accepted Answer
KSSV
on 30 Nov 2016
Edited: KSSV
on 30 Nov 2016
if exist('Test.txt','file')
%%do what you want
end
doc exist
You have to check this before opening file for writing, else it opens fresh file after fopen.
3 Comments
Jan
on 30 Nov 2016
Remember that exist('Test.txt','file') detects folders also. Althought it is usual to use ".txt" for a folder name, it is not forbidden. Then even asking for overwriting will not allow to create the text file.
More Answers (2)
Image Analyst
on 30 Nov 2016
You can do it like this:
filename = 'test.txt'; % Whatever it is.
overwriteFile = true; % Default to overwriting or creating new file.
if exist(filename, 'file')
% Ask user if they want to overwrite the file.
promptMessage = sprintf('This file already exists:\n%s\nDo you want to overwrite it?', filename);
titleBarCaption = 'Overwrite?';
buttonText = questdlg(promptMessage, titleBarCaption, 'Yes', 'No', 'Yes');
if strcmpi(buttonText, 'No')
% User does not want to overwrite.
% Set flag to not do the write.
overwriteFile = false;
end
end
if overwriteFile
% File does not exist yet, or the user wants to overwrite an existing file.
delete(filename);
fid = fopen(filename,.............
% More code to do the writing.....
end
2 Comments
Image Analyst
on 2 Dec 2016
Personally I think it's preferable to ask the user if your program can overwrite their existing file. That's why my code is a little longer. In fact I need to make it even longer by doing this:
recycle on
to make sure that when you delete their existing file, it shows up in the recycle bin. That way, their file is recoverable if they change their mind and need the original back.
Christian Long
on 27 Sep 2019
Edited: Christian Long
on 27 Sep 2019
You can also use the built-in file dialog to ask the user what they want to do. This gives them the opportunity to specify a new file name if they want to.
filename = 'test.txt'; % Whatever it is.
if exist(filename, 'file')
[file,path] = uiputfile({'*.txt','Text file (*.txt)';'*.*','All files (*.*)'},'Save File Name',filename);
end
0 Comments
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!