[英]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数组
char filename[100]
And use a for loop and have nested if statements that checks if each single character of the strings are !@%^*~| 并使用for循环并使用嵌套的if语句来检查字符串的每个字符是否都是!@%^ *〜| 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. 因为如果我这样做,我会有很多个人if语句来测试所有可能的非法字符。
You can use strchr
for that, and if the return is not null, you have found a bad character. 您可以使用strchr
,如果返回值不为null,则表示您找到了一个错误的字符。
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: 这可能是一个独特的解决方案(我的应用程序没有足够的信息,所以无论如何我都会发布),但是如果你只想要字母数字名称,你可以比较一系列字符的整数值,这很简单( r)如果声明:
If you want to see if its a lower/upper case or a number: 如果你想看看它是小写/大写还是数字:
//pseudo if(0-9, az, AZ)continue; //伪 if(0-9,az,AZ)继续;
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.