Check if filename is valid.

257 views (last 30 days)
Qingyang on 20 Jul 2012
Answered: Daniele Busi on 24 Feb 2020
Hi, is there a native function or a simple code to check if a user-typed filename is valid for saving a file? (In that it doesn't contain illegal characters like /\":?<>|, etc.)

Accepted Answer

Sean de Wolski
Sean de Wolski on 20 Jul 2012
regexp it!
Jason Nicholson
Jason Nicholson on 14 Feb 2014
This code snippet will not work unless you check if it is empty.
if ~isempty(regexp(filename, '[/\*:?"<>|]', 'once'))
%Do something

Sign in to comment.

More Answers (4)

Daniel Shub
Daniel Shub on 23 Jul 2012
A long time ago, probably Windows 95 on a FAT16 harddisk, I started using the following:
regexp(fname, ['^(?!^(PRN|AUX|CLOCK\$|NUL|CON|COM\d|LPT\d|\..*)', ...
'(\..+)?$)[^\x00-\x1f\\?*:\"><|/]+$'], 'once'));
At that time, Windows had the most restrictive file name conventions. I am not sure what the rules are now. You also should check for the length of the path and the total number of characters in the file name.
  1 Comment
Jan on 23 Jul 2012
Windows 7: Either 260 characters, or start with //?/ and 32767 characters, while each folder can have up to 255 characters. The later works for most of the API-functions, but not e.g. for the Windows Explorer. Moving a file name with a long name to the RecycleBin fails also. The backup program and server based tools might fail also. Therefore I'd prefer the dull limit of 260 characters (including "C\:" and a trailing terminator '\0')!).

Sign in to comment.

ola bayo
ola bayo on 16 Oct 2017
Edited: Walter Roberson on 16 Oct 2017
Which following is a valid file name in MATLAB?
A) lab 2
B) lab2
C) lab-2
D) 2lab
E) LAB 2
  1 Comment
Walter Roberson
Walter Roberson on 16 Oct 2017
For the question as phrased: all of them. For a slightly different question, the answer would be fairly different.

Sign in to comment.

Thomas on 1 Dec 2017
If you do not want to use UIputfile, another option is fopen. fileID = fopen(filename,'w') if fopen cannot open the file, then fileID is -1.

Daniele Busi
Daniele Busi on 24 Feb 2020
function bool = isLegalPath(str)
bool = true;
bool = false;

Community Treasure Hunt

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

Start Hunting!