File Exchange

image thumbnail

Next Available Filename

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


Updated 13 Sep 2017

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. Because of how DIR works file names must contain a file extension.

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 number of leading zeros (can be zero or more).
* 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', 'A3.m', and 'A5.m':

ans = A0.m

ans = A4.m

ans = A23.m

ans = A005.m

Comments and Ratings (1)

Shinuo Weng

Exactly what I need.


* Add check for no matching files.

* Update HTML docs.

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

Discover Live Editor

Create scripts with code, output, and formatted text in a single executable document.

Learn About Live Editor