Pergunta

I wanted to make the program accomplish "execvp(argv[1],argv+1);" if the first argument is undefined, but getopt parsing all arguments starting with "-". How to ignore all the arguments after the first undefined argument? Is this possible using getopt? Currently, I have code:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
void print_usage() {
     printf("Usage: here print usage\n");
}

int main(int argc, char *argv[]) {
    int option = 0;
char user[32]={0}, command[50]={0};
while ((option = getopt(argc, argv,"c:u:h")) != -1) {
    switch (option) {
         case 'c' : strcpy(command,optarg);
             break;
         case 'u' : strcpy(user,optarg);
             break;
         case 'h' : print_usage();
                    exit(EXIT_SUCCESS);
             break;
         default:
             print_usage();
             exit(EXIT_SUCCESS);
    }
}

if(strlen(user)!=0) {
    if (strlen(command)!=0)
        printf("execute %s for %s\n",command,user);
    else
        printf("please specify command\n");
}
else {
    if (strlen(command)!=0)
        printf("please specify user\n");
    else if (argc > 2)
         printf("execute %s for everyone\n",argv[1]);

}

return 0;

}

When you execute, I got:

./thisprogram ls -l
./thusprogram: invalid option -- 'l'

I would like to make like this;

./thisprogram ls -l /
razem 52
lrwxrwxrwx   1 root root     7 05-31 20:40 bin -> usr/bin
drwxr-xr-x   5 root root  4096 10-21 22:44 boot
drwxr-xr-x  19 root root  3160 11-02 17:10 dev

and so on... but I have no idea.

Foi útil?

Solução

Just stop parsing when you encounter an unknown argument.

int done = 0;
while (!done && (option = getopt(argc, argv,"c:u:h")) != -1) {
    switch (option) {
     ...
    default:
        done = 1;
        break;
   }
}

(or if you want, , use case '?': instead of the default: case,as getopt returns '?' when it encounters an unknown argument)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top