-
isprint() 需要 ctype
- 不确定 - 如果您不在
main 函数中执行此操作,它可能会稍微有用,但打印错误然后调用 exit(1) 可能会更好;我想这只是一个最小的例子,一行比两行短
-
这里有几个你可能会觉得有用的链接:
简而言之:
optopt、optind 和 optarg 是外部符号。它们是全局的,并在 unistd.h 中声明。
optopt (opt = option) 通常不需要。应该和调用getopt返回的值一样。
optarg (arg = argument) 很简单。这是一个标志的参数。例如如果-f 是一个需要文件名参数的选项(optstring 包含f:),你可以这样做
case 'f':
filename = optarg;
break;
optind(ind 表示index)告诉您在您的while (flag = getopt...) 块结束后选项过程在哪里完成。
例如在添加选项处理之前,您的脚本可能如下所示
// print command line arguments, start at 1 to skip the program name
for (int i = 1; i < argc; i++) {
printf("arg[%d]=%s\n", i, argv[i]);
}
添加 getopt 块来处理选项后,您可以这样做
// print command line arguments remaining after option processing
for (int i = optind; i < argc; i++) {
printf("arg[%d]=%s\n", i, argv[i]);
}
或
// skip command line options
argc -= optind; argv += optind;
// print command line arguments
for (int i = 0; i < argc; i++) {
printf("arg[%d]=%s\n", i, argv[i]);
}
如果您没有任何必需的命令行参数,那么您不必担心optind。