[英]Getopt not recognizing command line arguments (C program)
我正在 CentOS linux 中创建 C 程序,我无法让我的 getopt 从命令行识别 ZDBC11CAABD5BDA99FD77E6FB4。 我对 linux 和 C 比较陌生。
我得到的错误是'找不到命令'我使用 gcc 编译文件并使用./testFile 编译命令执行是: gcc mathwait.c 然后 -testFile
感谢您的帮助!
void help()
{
printf("The options for this program are:\n ");
printf("-h - walkthrough of options and program intent\n ");
printf("This program forks off a single child process to do a task\n ");
printf("The main process will wait for it to complete and then do\n");
printf("some additional work\n");
}
int main(int argc, char **argv)
{
int option;
while((option = getopt(argc, argv, "h")) != -1)
{
switch(option)
{
case 'h':
help();
break;
default:
help();
break;
}
}
}
#include <stdio.h>
#include <unistd.h>
并且您缺少退货声明:
return 0;
如果没有更多选项字符,getopt() 返回 -1
这意味着如果您不提供任何 arguments getopt()
将返回 -1 并且您的while()
循环不会被执行并且您的程序将退出。 如果您使用-h
调用程序,将执行第一个案例,否则(意味着任何其他参数)将执行default
案例。
我假设这是测试代码,否则当你在所有情况下都做同样的事情时,没有必要进行切换。
格式化对可读性很重要:
#include <stdio.h>
#include <unistd.h>
void help() {
printf(
"The options for this program are:\n"
"-h - walkthrough of options and program intent\n"
"This program forks off a single child process to do a task\n"
"The main process will wait for it to complete and then do\n"
"some additional work\n"
);
}
int main(int argc, char **argv) {
int option;
while((option = getopt(argc, argv, "h")) != -1) {
switch(option) {
case 'h':
help();
break;
default:
help();
break;
}
}
return 0;
}
你说:
编译命令是:
gcc mathwait.c -o testFile
然后./testFile
如果您运行./testFile
,则您没有提供任何 arguments。 跑:
./testFile -h
现在您为getopt()
处理提供了一个选项。 如果您运行./testFile -x
,您会收到一条关于无法识别的选项'x'
的消息,然后是来自help()
function 的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.