Writting multiple files with fopen 'w'
조회 수: 4 (최근 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
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
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
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!