In scenarios where you want to save a file and the file name is generated programmatically, you may want to check whether the file name has been taken by another file in the same path. In this case, GETUNIQUEFILENAME generates a new file name by adding a suffix to the original file name with a specified pattern.
OutFile = getUniqueFileName(InFile, Argments);
InFile: file name including file path and extension. File path can be skipped if it is the current Matlab path.
OutFile: if no conflict, the original file name if conflicting, a file name suffixed with a sequential integer enclosed in parenthesis. Sequential integer starts from 1.
Arguments: one or both of the following:
- an integer: custom start number for the sequential integer.
- formatting spec:
string formatting spec: must include one and only one operator '%d', additional operators may cause error or unexpected file name.
datetime format spec: use formatted datetime string as suffix, now is used to get the serial date number.
'DefaultDateSpec': uses '_ddmmyy-HHMMSSFFF' as the datetime format spec
Note: If a datetime suffixed filename still conflicts with one of the existing file's name, ' (%d)' will be suffixed.
Example:
For a file structure:
X:/
|- file.txt
|- file (1).txt
|- file (2).txt
Commands:
fname = 'X:/file.txt';
NEWFILE_1 = getUniqueFileName(fname);
NEWFILE_2 = getUniqueFileName(fname, 5);
NEWFILE_3 = getUniqueFileName(fname, '_%d');
NEWFILE_4 = getUniqueFileName(fname, 0, '_v%d');
NEWFILE_5 = getUniqueFileName(fname, '_dd-mm-yy_HH-MM-SS-FFF');
NEWFILE_6 = getUniqueFileName(fname, 'DefaultDate');
Results:
NEWFILE_1 = X:/file (3).txt
NEWFILE_2 = X:/file (5).txt
NEWFILE_3 = X:/file_1.txt
NEWFILE_4 = X:/file_v0.txt
NEWFILE_5 = X:/file_01-01-1900_00-00-00-000.txt
NEWFILE_6 = X:/file_0101190000-0000000.txt
引用格式
Zhengyi (2024). getUniqueFileName(file, varargin) (https://www.mathworks.com/matlabcentral/fileexchange/67274-getuniquefilename-file-varargin), MATLAB Central File Exchange. 检索时间: .
MATLAB 版本兼容性
平台兼容性
Windows macOS Linux类别
标签
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!