所以,我有下一个代码:
#include<unistd.h>
#include<getopt.h>
#include<getopt.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
// #include"main.hpp"
// #include"functions.cpp"
int main(int argc, char** argv) {
opterr = 0;
int f_verbose = false;
int option_index = 0;
static struct option long_options[] =
{
{"file", required_argument, NULL, 'f'},
{"verbose", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{"version", no_argument, NULL, 1},
{NULL, 0, NULL, 0},
};
int arg;
char* file_path = NULL;
while( -1 != (arg = getopt_long(argc, argv, ":f:hv", long_options, &option_index)) ) {
switch(arg) {
// case 0: // long options
// if (long_options[option_index].flag != 0)
// break;
case ':':
fprintf(stderr, "No argument(s) provided for '%s' option.\n", argv[optopt]);
// read_help(*argv);
exit(EXIT_FAILURE);
case '?':
fprintf(stderr, "Unknown option: '%s'.\n", argv[optopt]);
// read_help(*argv);
exit(EXIT_FAILURE);
case 'f':
errno = 0;
file_path = (char*)malloc(sizeof(*optarg)*(strlen(optarg) + 1));
if (file_path == NULL) {
fprintf(stderr, "Could not allocate memory: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'v':
f_verbose = true;
break;
case 'h':
printf("Usage: %s -f filename [-v | --verbose] [-h | --help]\n"
"\n"
"Avaliable options:\n"
" -f, --file <filename>\n"
" Get lines coordinates from <filename>.\n"
" -v, --verbose\n"
" Print execution time\n"
" -h, --help\n"
" Print help message\n"
" --version\n"
" Print version.\n"
"\n"
"Program purpose:\n"
"You should pass filename of file, first\n"
"two strings containing two numbers of 2D\n"
"plane coordinates of lines ends in each.\n"
"Program have to calculate and print lines\n"
"interception coordinates, if there is some.\n",
*argv);
exit(EXIT_SUCCESS);
case 1: // --version
printf("v1.0, mod 3, NAU, Vladyslav Rehan, 2023.\n");
exit(EXIT_SUCCESS);
default:
printf("ENTERED DEfAULT\n");
abort();
}
}
printf("END\n");
}
当我编译它并传递错误的选项时,我得到
getup_long
提供的分段错误或未知选项错误我猜:
➜ Mod_1 g++ main.cpp
➜ Mod_1 ./a.out --unknown
Unknown option: './a.out'.
➜ Mod_1 ./a.out -a
[1] 18507 segmentation fault ./a.out -a
➜ Mod_1 ./a.out -c
[1] 18517 segmentation fault ./a.out -c
➜ Mod_1 ./a.out --what
Unknown option: './a.out'.
➜ Mod_1 ./a.out -v
END
➜ Mod_1 ./a.out --version
v1.0, mod 3, NAU, Vladyslav Rehan, 2023.
➜ Mod_1 ./a.out --v
Unknown option: './a.out'.
➜ Mod_1 what is happening
如果我设置了
Unknown option: './a.out'.
,为什么我会得到opterr = 0;
?
为什么会出现分段错误?
而且,我现在做
optind-1
技巧,但它不能与 ./a.out -ac
一起正常工作,例如:
➜ Mod_1 ./a.out -ac
Unknown option: './a.out'.
再次出现一些神秘的错误信息。
我已经看了十遍 GNU Clib 文档,它说
getopt_long
和 getopt
的工作原理相同所以 opterr = 0;
和 int optopt
应该是有道理的。或者我误解了什么?
首先,f_verbose 应该是 boot 而不是 int。因此,要做到这一点,您只需添加库 stdbool,方法是:
#include