File Exchange

image thumbnail

Next Available Filename

version 1.2.1 (6.68 KB) by Stephen Cobeldick
Returns the next unused file or folder name. The name is created by incrementing a numbered suffix.

9 Downloads

Updated 12 Sep 2019

View License

Returns the next available filename or foldername, creating the name by incrementing a numbered suffix.

On occasion it may be required to save files without knowing or requiring a particular number sequence, for example when saving interim results or backups during large calculations. Using an internal counter is one option, but this does not work when there are already existing files with those names, or when the code is stopped-and-started or throws errors. This function offers one simple solution: call the function with the required file (or folder) name and the required suffix and it will return the next unused name.

%% Inputs %%

Only two inputs are required:

1. The file or folder name string (1xN char), either a relative or absolute path.

2. the suffix string (1xN char), which must contain the starting number. Some examples of suffixes are: '0', '_1', '(5)', '.backup.0001', '_temp_050', etc.. This suffix will be appended to the file/folder name, and the number will be incremented to identify the first unused name starting from the number provided in the suffix. Thus the suffix controls:

* the starting number (zero or any positive integer, e.g. 0, 1, 2, etc).
* the minimum length of the output number (use leading zeros as required).
* any literals and other required characters (note: this function does not check if the literals are permitted by the filesystem. User beware!)

%% Examples %%

Given a directory containing files 'A1.m', 'A2.m', and 'A4.m':

nextname('A.m','0')
ans = A0.m

nextname('A.m','1')
ans = A3.m

nextname('A.m','001')
ans = A003.m

Cite As

Stephen Cobeldick (2019). Next Available Filename (https://www.mathworks.com/matlabcentral/fileexchange/64108-next-available-filename), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Shinuo Weng

Exactly what I need.

Updates

1.2.1

* Improve efficiency.

1.2.0

* Handle single matched subfolder.

1.1.0.0

* Add check for no matching files.

1.0.0.0

* Update HTML docs.

MATLAB Release Compatibility
Created with R2010b
Compatible with any release
Platform Compatibility
Windows macOS Linux