getopt()
可以,但如果您的需求很小,并且不想添加外部依赖项,可以编写自己的小助手函数来查找短划线关键字在
argv
数组,如下所示:
#include
#include
#include
// Returns the index of the specified keyword (e.g. "-oh")
// or returns -1 if the keyword doesn't exist
static int find_keyword(int argc, char *argv[], const char * keyword)
{
for (int i=0; i
{
if (strcmp(argv[i], keyword) == 0) return i;
}
return -1;
}
int main( int argc, char* argv[] )
{
const int iIndex = find_keyword(argc, argv, "-i");
if (iIndex < 0) {printf("No -i keyword found! Exiting!\n"); exit(10);}
const int osIndex = find_keyword(argc, argv, "-os");
if (osIndex < 0) {printf("No -os keyword found! Exiting!\n"); exit(10);}
const int ohIndex = find_keyword(argc, argv, "-oh");
if (ohIndex < 0) {printf("No -oh keyword found! Exiting!\n"); exit(10);}
take_input( argv[iIndex+1] );
make_output( argv[osIndex+1], argv[ohIndex+1] );
}
注意,如图所示的程序不会检查破折号参数之后的下一个参数是否存在;例如,如果运行“./a.out-ifoo-os bar-oh”,则make_output的第二个参数将作为NULL传入。你可以修改
find_keyword()
如果您希望在错误处理中更加健壮,请检查这种可能性并在这种情况下返回-1。