[英]C Prevent more than 30 character input
Hi I'm having an issue with my code. 嗨,我的代码有问题。 I need it to run so that if the user enters more than 30 characters for the "fileName" variable it will "return;"
我需要运行它,以便如果用户为“ fileName”变量输入超过30个字符,它将“返回”; but the code I have below doesn't work.
但是我下面的代码不起作用。 Any ideas?
有任何想法吗?
FILE *packetFile; //initialize file handle
char fileName[30]; //initialize
int i;
int length = 0;
length = strlen(fileName);
getchar();
printf("Please enter a file name (Maxium 30 characters): ");
fgets(fileName, 30, stdin);
sscanf(fileName, "%s", fileName);
if(fileName[0] == '\n'){
return;
}
if(strlen(fileName) > 30)
return;
if((packetFile = fopen(fileName,"w"))==NULL) {
printf("Unable to open the file: %s\n",fileName);
} else {
printf("%d packets have been saved to file named %s", pCount, &fileName);
for(i=0;i<pCount;i++) {
fprintf(packetFile,"%04i:%04i:%04i:%04i:%s\r\n",pRecords[i].source,pRecords[i].destination,pRecords[i].type,pRecords[i].port,pRecords[i].data);
}
fclose(packetFile);
}
Multiple reasons. 有多种原因。 You're only allocating room for 30 characters, so a
strlen
will never return a result > 30
in your case. 您只分配30个字符的空间,因此
strlen
永远不会返回> 30
的结果。 You're also only reading max 30 chars in your fgets
call. 您在
fgets
调用中最多只能读取30个字符。
A possible fix is to allocate more space to begin with and use strlen
. 可能的解决方法是分配更多空间开始使用
strlen
。 Another solution is to keep the limited allocation, and use a loop to read individual characters from stdin
- if you don't reach a newline character in time, you just break out and return. 另一个解决方案是保持有限的分配,并使用循环从
stdin
读取单个字符-如果您没有及时到达换行符,则只需中断并返回即可。
On POSIX systems, getline
provides a neat solution. 在POSIX系统上,
getline
提供了一个简洁的解决方案。 It reads a whole line, and it returns the length. 它读取整行,并返回长度。 Only thing to remember is that
getline
allocates memory on the heap, so you need to free it when you're done. 唯一要记住的是
getline
在堆上分配内存,因此您需要在完成后释放它。
Something along the lines of: 类似于以下内容:
char *filename = NULL;
size_t linecap = 0; // These initial values tells getline to allocate as much space as needed
ssize_t linelen = getline(&filename, &linecap, stdin);
if (linelen < 0)
...
if (linelen > 30)
// Treat as error or whatever
free(filename);
(shameless borrowing from the man page) (从手册页无耻地借用)
char fileName[30+2];//+1 for '\n', +1 for '\0'
int i;
int length = 0;
printf("Please enter a file name (Maxium 30 characters): ");
fgets(fileName, sizeof(fileName), stdin);
if(fileName[0] == '\n'){
return;
}
length = strlen(fileName);
if(fileName[length-1]!='\n'){
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.