Validating User Input for Filenames

c

Solution

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");
}

Problem

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.

Original source