So I have a question about flags and arguments in C from argv array.
When I enter a commant through terminal:
Example: ./main a b c -a
It does not recognize that -a at the end but if I put it at the beginning of all arguments like: ./main -a a b c
it will detect it.
I tried swapping it with if so it would be in the front of all argumetns, but after a swap it doesnt proceed. Something like ignoring the for loop after it. So it just swaps it and then ends the case. If anyone know what am I missing here I would be happy.
Code:
while ( (c = getopt(argc, argv, ":ahd:")) != -1) {
switch (c) {
case 'a':
if(strcmp(argv[argc-1], "-a") == 0){
swap(&argv[argc-1], &argv[1]);
}
for(i = optind; i < argc; i++){
for(j = optind; j < argc - 1; j++){
if(strcmp(argv[j], argv[j + 1]) > 0){
swap(&argv[j], &argv[j + 1]);
}
}
}
for(z = optind; z < argc; z++){
printf("%s\n", argv[z]);
}
printf("%s\n", argv[1]);
break;
The GNU version of getopt()
allows for permutation of arguments so that all -a
style options (that appear before a --
option) will be processed, even if there are non-option arguments before them.
some_program -z abc def -b -- -w warning
The -z
and -b
options would be recognized by GNU getopt()
, but the -w
would be a non-option argument.
The POSIX version of getopt()
does not allow this; many non-GNU implementations of getopt()
do not do this. GNU knows that what they do is an extension; the permute behaviour can be turned of by setting POSIXLY_CORRECT
in the environment.
If you want options to be recognized anywhere, use the GNU getopt()
in your program. If you want to use the local getopt()
to remain portable, or can't afford to use GPL code in your programs, design your system to put options before non-option arguments. Note that programs like make
and the C compilers already have custom argument handling systems that allow the interleaving of options and non-option arguments — but you should follow POSIX coding guidelines (Utility Conventions) for option handling unless you have a strong reason to do otherwise.