最近我一直在使用getopt
(来自unistd.h)玩耍。我写了一些代码,在Windows 7上使用MinGW编译器正常运行,但是在我的树莓派上的Raspbian Linux下不工作(我用gcc编译它们两个,没有选项;gcc t.c
)。由于某种原因,当面临没有开关时,getopt返回int 255或char ÿ,而实际上应该返回-1。
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char t;
opterr = 0;
while ((t = getopt(argc, argv, "a:")) != -1)
switch (t) {
case 'a':
printf("-a with argument %s\n", optarg);
return 0;
case '?':
printf("uknown option\n");
return 1;
default:
/* This is always 255 under linux, and is never reached under windows */
printf("getopt returned int %d (char %c)\n", t, t);
return 2;
}
return 0;
}
我有一个想法,实际上在无符号8位算术中,255 就是-1,所以我尝试在while条件语句中放入int强制转换,但这没有起作用。
char t;
改为int t;
,问题就解决了。(-1 表示 EOF,或者在这种情况下表示没有更多的选项。你可以通过添加case -1: break;
来处理它。) - wildplassergetopt
函数从未返回EOF
。当无法找到更多选项时,它会返回 -1。 - Carl Norumsscanf
确实会返回EOF
常量,不是吗?只是在大多数系统上EOF
是-1
是巧合。无论如何,这就是我想要澄清的 - 在“文件结尾”的语义和字面使用EOF
作为常量之间的区别。 - Carl Norum