C / C ++中的错误参数处理 [英] Bad argument handling in C/C++
问题描述
当我运行我的程序,如 ./程序abcd
而不是
When I run my program like ./program a b c d
instead of
./program -i inFile -o outFile
它告诉我文件打开有问题(这是真的)但是
it tells me something is wrong with the file opening (which is true )but
Expected: "Usage: program -i inputfile -o outputfile\n"
Got: "Error: Cannot open file /no/such/file\n"
你知道吗我该怎么处理这个?任何线索?
这也是我的代码处理不好的参数处理的一部分:
Do you know how should I handle this? Any clue? Also this is part of my code which deals with bad argument handling:
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);
}
推荐答案
我所能做的只是重复您的之前的答案问题,我认为这是正确的答案。
Well all I can do is repeat the answer to your earlier question, which I think was the correct answer all along.
请参阅inFile和outFile为NULL,然后在您的getopts循环之后检查是否还是NULL。如果他们打印使用信息并退出
See inFile and outFile to NULL, then after your getopts loop check to see if either is still NULL. If they are then print the usage message and exit
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);
您将代码中的错误位置放在File和outFile中。它应该在之后 while循环。您正在做的是检查较早的while循环是否设置了 inFile
和 outFile
中的值,并向用户抱怨如果没有。正如我之前所说,我不认为 if(argc!= 5)
是有帮助的,我只会删除它。
You placed the check on inFile and outFile in the wrong place in your code. It should go after the while loop. What you are doing is checking if the earlier while loop sets the values of both inFile
and outFile
and complaining to the user if it does not. And as I said before I don't think if (argc != 5)
is helpful, I would just delete it.
这篇关于C / C ++中的错误参数处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!