简体   繁体   中英

Validating User Input for Filenames

If I was to let a user input a filename for a file (allowing spaces) and validate it to see if it is a bad file name, how would I do so?

The only way right now that I can think of is to create char array like

char filename[100]

And use a for loop and have nested if statements that checks if each single character of the strings are !@%^*~| and etc by writings lines like these

for(...) {
    if(filename[i] == '@'){...}
    if(filename[i] == '!'){...}
}

Are there better ways to approach this? Because if I was to doing it like that, I would have A LOT of individual if statements just to test all the possible illegal characters.

You can use strchr for that, and if the return is not null, you have found a bad character.

char bad_chars[] = "!@%^*~|";
char invalid_found = FALSE;
int i;
for (i = 0; i < strlen(bad_chars); ++i) {
    if (strchr(filename, bad_chars[i]) != NULL) {
        invalid_found = TRUE;
        break;
    }
}
if (invalid_found) {
    printf("Invalid file name");
}

You could try regex:

#include <stdlib.h> 
#include <string.h>
#include <regex.h>

int main (void) {
    char fileName[100];
    int comp; 
    regex_t myregex; 

    // Compile the regular expression 
    comp = regcomp(&myregex, "^[a-zA-Z0-9.' '\[\]_-]+$", REG_EXTENDED | REG_NOSUB) ;

    printf("Enter a file name\n");
    scanf("%s",fileName) ; 

    // Compare fileName to the regex 
    if (!regexec(&myregex, fileName, 0 , 0 , 0)) {
        printf("fileName %s is valid.\n", fileName);  
    } else {
        printf("fileName %s is invalid.\n", fileName);
    }
    return 0;
}

This maybe a unique solution (I don't have enough info on your application, so I will post it anyway), but if you only want alphanumeric names, you can compare the integer value of a range of characters which would be a simple(r) if statement:

If you want to see if its a lower/upper case or a number:

//pseudo if(0-9, az, AZ)continue;

else reject;

for(i=0;...;...){
    if((filename[i]==32)||(filename[i]>47 && filename[i]<58 )||(filename[i]>64 && filename[i]<91)||
    (filename[i]>96 && filename[i]<123))
        continue;
else{
...//reject filename
}

Alternatively you can see if its a non-alphanumeric...

for(i=0;...;...){
    if((filename[i]<=47) || (filename[i]<=64 && filename[i]>=58) ||
    (filename[i]<=96 && filename[i]<=91) || (filename[i]<=123)){
        reject;
    else{
        ...//nothing
    }

http://www.asciitable.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM