How to ask user before overwriting a text file?

10 次查看(过去 30 天)
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!');

采纳的回答

KSSV
KSSV 2016-11-30
编辑:KSSV 2016-11-30
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 个评论
Jan
Jan 2016-11-30
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.

请先登录,再进行评论。

更多回答(2 个)

Image Analyst
Image Analyst 2016-11-30
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 个评论
Image Analyst
Image Analyst 2016-12-2
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
Christian Long 2019-9-27
编辑:Christian Long 2019-9-27
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

类别

Help CenterFile Exchange 中查找有关 Data Type Conversion 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by