当我像 ./program a b c d
而不是
./program -i inFile -o outFile
它告诉我文件打开有问题(这是真的)但是
Expected: "Usage: program -i inputfile -o outputfile\n"
Got: "Error: Cannot open file /no/such/file\n"
你知道我应该怎么处理吗?有什么线索吗? 这也是我处理错误参数处理的代码的一部分:
if ((s= strrchr( argv[0], '\\')) /* get filename w/o .exe extension */
|| (s= strrchr( argv[0], '/')))
s++;
else
s= argv[0];
if(inFile == NULL || outFile == NULL) {
error_usage(s);
}
if ( argc !=5 )
{
error_usage(s);
return -1;
}
while ((c = getopt(argc, argv, "i:o:")) != -1) {
switch (c) {
case 'i':
inFile = strdup(optarg);
break;
case 'o':
outFile = strdup(optarg);
break;
default:
error_usage(s);
}
}
if (!(iFile = fopen(inFile, "r+"))) {
fprintf(stderr, "Error: Cannot open file %s\n", inFile);
exit(1);
}
最佳答案
好吧,我所能做的就是重复你的 earlier question 的答案。 ,我一直认为这是正确的答案。
查看 inFile 和 outFile 为 NULL,然后 after 您的 getopts 循环检查是否仍然为 NULL。如果他们然后打印使用消息并退出
inFile = outFile = NULL;
while ((c = getopt(argc, argv, "i:o:")) != -1) {
switch (c) {
case 'i':
inFile = strdup(optarg);
break;
case 'o':
outFile = strdup(optarg);
break;
default:
error_usage(s);
}
}
if (inFile == NULL || outFile == NULL)
error_usage(s);
您将检查 inFile 和 outFile 的代码放在了错误的位置。它应该在 while 循环之后。您正在做的是检查较早的 while 循环是否设置了 inFile
和 outFile
的值,如果没有则向用户投诉。正如我之前所说,我认为 if (argc != 5)
没有帮助,我会删除它。
关于c - C/C++ 中错误的参数处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18952763/