Check if filename is valid.
Afficher commentaires plus anciens
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.)
Réponse acceptée
Plus de réponses (5)
Daniel Shub
le 23 Juil 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 commentaire
Jan
le 23 Juil 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')!).
ola bayo
le 16 Oct 2017
Modifié(e) : Walter Roberson
le 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 commentaire
Walter Roberson
le 16 Oct 2017
For the question as phrased: all of them. For a slightly different question, the answer would be fairly different.
Thomas
le 1 Déc 2017
0 votes
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
le 24 Fév 2020
function bool = isLegalPath(str)
bool = true;
try
java.io.File(str).toPath;
catch
bool = false;
end
end
George Abrahams
le 19 Déc 2023
Modifié(e) : George Abrahams
le 19 Déc 2023
0 votes
Like @Daniele Busi's answer, it's based on java.io.File().toPath, which is more robust than anything we'll build ourselves, but isvalidpath also provides:
- The option to validate that the path refers to a file, rather than a directory, or vice versa.
- The option to validate that the file extension matches a given set, for example, that the path refers to an image.
- Human readable feedback, in case the validation fails, for example, a warning that the path lacks a filename or contains an illegal character.
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!