Writting multiple files with fopen 'w'

6 次查看(过去 30 天)
fileID = fopen('text\test.txt','w');
fprintf(fileID,'Comments:');
fclose(fileID);
Hi,
What can I do to not overwrite the previous file
There is a way for every time I run the script to make another file and not rewritte the old one, like test1.txt, test2.txt and so on?

采纳的回答

Voss
Voss 2022-5-20
Here's a function (get_unused_file_name) you can use for this purpose. It takes a file name and check if that file already exists. If it does, the function appends '1' to the name and checks if that exists. If it does, it tries '2', and so on until it gets one that doesn't already exist, and returns that unused file name.
Here's a demonstration of it:
fn_orig = fullfile(pwd(),'text','test.txt') % file name to try
fn_orig = '/users/mss.system.Cr4l4C/text/test.txt'
mkdir('text')
% calling the function 4 times
for ii = 1:4
fn = get_unused_file_name(fn_orig)
% create the file so that next time around
% this file name is already taken:
fid = fopen(fn,'w');
fclose(fid);
end
fn = '/users/mss.system.Cr4l4C/text/test.txt'
fn = '/users/mss.system.Cr4l4C/text/test1.txt'
fn = '/users/mss.system.Cr4l4C/text/test2.txt'
fn = '/users/mss.system.Cr4l4C/text/test3.txt'
function file_name = get_unused_file_name(file_name)
[pn,fn,ext] = fileparts(file_name);
ii = 0;
while isfile(file_name)
ii = ii+1;
file_name = fullfile(pn,sprintf('%s%d%s',fn,ii,ext));
end
end
  7 个评论
Cristian Martin
Cristian Martin 2022-5-20
Indeed I use 2015a, and with exist its perfect functional. Now I get the ideea, but still I'm tired. Thank you for your patience and kindness!
Voss
Voss 2022-5-20
You're welcome! Sorry about the snag with isfile, but I'm glad it's working now!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品


版本

R2015a

Community Treasure Hunt

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

Start Hunting!

Translated by