을하지 않는 것 (파일이라고 testgetopt.c에 저장) :C : getopt는은() : 옵션이 적용에게 나는 다음과 같은 C 코드를 시도하고
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <ctype.h>
void usage(char *s)
{
fprintf(stderr, "Usage: %s [-d] -i input-TIFF-file -o output-raw-file\n", s);
fprintf(stderr, "Note: -d indicates debugging option\n");
}
int main(int argc, char **argv) {
char c;
size_t i;
char *itext = NULL, *otext = NULL;
FILE *fout;
short debug = 0;
if ((c = getopt(argc, argv, "di:o:")) == EOF) {
usage(argv[0]);
exit(1);
}
while ((c = getopt(argc, argv, "di:o:")) != EOF) {
switch (c) {
case 'd':
debug = 1;
break;
case 'i':
itext = optarg;
break;
case 'o':
otext = optarg;
break;
case '?':
if (optopt == 'i' || optopt == 'o')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
else if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr, "Unknown option character `\\x%x'.\n", optopt);
usage(argv[0]);
exit(1);
default:
fprintf(stderr, "Both -i and -o are needed\n");
usage(argv[0]);
exit(1);
}
}
printf("debug = %i\n", debug);
if (debug)
printf ("input file = %s, output file = %s\n", itext, otext);
return EXIT_SUCCESS;
}
내가 사용 컴파일
gcc testgetopt.c
하지만 -d를 포함하든 그렇지 않든 관계없이 항상 0으로 설정된 디버그를 얻습니다. 프로그램에서 -d 디버그를 1로 설정하고 그렇지 않으면 0으로 설정해야합니다.
무엇이 잘못 되었습니까?
다음은 예입니다
은 우리가 처음 -d 포함 우리가 다음에 해보자없는 -d
./a.out -i in.dat -o out.dat
debug = 0
함께 해보자.
./a.out -d -i in.dat -o out.dat
debug = 0
도움이나 제안을 보내 주셔서 감사합니다.
어떻게 디버그를 시도 했습니까? 루프 내에서 getopt의 결과를 출력하면 어떤 일이 벌어지고 있는지에 대한 이론을 세울 수 있습니다. 일종의 stack-overflower가 그 일을 충분히 해냈습니다. –