How to ask user before overwriting a text file?

조회 수: 14 (최근 30일)
Shar
Shar 2016년 11월 30일
편집: Christian Long 2019년 9월 27일
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.
Shar
Shar 2016년 12월 2일
Thanks!

댓글을 달려면 로그인하십시오.

추가 답변 (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
Shar
Shar 2016년 12월 2일
Thanks!
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에서 String Parsing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by