How to ask user before overwriting a text file?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Shar
el 30 de Nov. de 2016
Editada: Christian Long
el 27 de Sept. de 2019
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 comentarios
Respuesta aceptada
KSSV
el 30 de Nov. de 2016
Editada: KSSV
el 30 de Nov. de 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 comentarios
Jan
el 30 de Nov. de 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.
Más respuestas (2)
Image Analyst
el 30 de Nov. de 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 comentarios
Image Analyst
el 2 de Dic. de 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
el 27 de Sept. de 2019
Editada: Christian Long
el 27 de Sept. de 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 comentarios
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!