I needed a function to tell me if a filename would be valid for DOS. It took a little more effort to write than I thought it would. Does anybody know of a better way to do this?
Performance could be better with a SCASB instruction, but don't worry about that now ...
Just to review, the rules are:
Mike
Code:
#include <stdio.h>
#include <string.h>
// I use char for return codes because only a single byte integer is needed
// and that is more efficient on 8088 machines. If you see char as a return
// code just think of a single byte integer.
char DosChars2[] = "!@#$%^&()-_{}`'~";
char isValidDosChar( char c ) {
// A-Z, a-z, 0-9 and any char above 127 are legal
if ( (c >='A') && (c<='Z') || (c >='a') && (c<='z') ||
(c >='0') && (c<='9') || (c > 127)
) return 1;
// Is it one of the acceptable punctuation chars?
for ( char i=0; i<16; i++ ) {
if ( c == DosChars2[i] ) return 1;
}
return 0;
}
char isValidDosFilename( const char *filename ) {
// Protect against incoming NULL strings
if (filename==NULL) return 0;
char len = strlen(filename);
// Reject zero length strings
if ( len == 0 ) return 0;
// Check the first character - it has to be valid and it cant be a '.'
// because a filename is not optional (but extensions are).
if ( !isValidDosChar( filename[0] ) ) return 0;
// Check the remainder of the filename part; stop when a '.' is found
int i;
for ( i=1; (i<8) && (i<len) ; i++ ) {
if ( filename[i] == '.' ) break;
if ( !isValidDosChar( filename[i] ) ) return 0;
}
// End of string - Ok, there is no extension
if ( i == len ) return 1;
// We are on the 9th char - this better be a '.'
if ( filename[i] != '.' ) return 0;
i++;
for ( int j=0; (j+i) < len; j++ ) {
if ( !isValidDosChar( filename[j+i] ) ) return 0;
}
// Is the extension too long?
if ( j > 3 ) return 0;
return 1;
}
int main( int argc, char *argv[] ) {
printf( "%s\n", (isValidDosFilename(argv[1])) ? "Yes" : "No" );
return 0;
}
Performance could be better with a SCASB instruction, but don't worry about that now ...
Just to review, the rules are:
- Up to 8 characters for the filename
- Up to 3 characters for an extension
- Filenames are required - extensions are not
- Only certain characters are allowed/safe
Mike
Last edited: