getopt in bestimmter reihenfolge auswerten



  • ich habe eine kleines problem mit getopt eine option (-p) braucht auch die Option (-x) und (-y) um was auszugeben.

    hier der code:

    int command;
    int x=0, x=0;
    
     while ((command = getopt(argc, argv, "p:x:y:")) > 0) 
      {
        switch (command)
         {
          case 'x': x = atoi(optarg);
          		break;
          case 'y': y = atoi(optarg);
          		break;
          case 'p': 
    		printText(optarg, x, y); 
    		break;
         }
      }
    

    Jetzt klappt das nur in einer bestimmten reihen folge nämlich dann wenn die option -p am schluss steht. Klar da ja die optionen -x und -y vorher gestzt werden.
    Wie kann ich das umgehen das man die optionen in x beliebiger reihenfolge schreiben kann aber die optionen -x und -y immer zuerst behandelt werden ?

    MFG
    xmarvel



  • ich kenne getopt nicht, aber du könntest dir da ein flag setzen:

    print = false;
    
      ...
        switch (command)
         {
          case 'p':
            print = true;
            break;
         }
      } 
    
    if(print)
        printText(optarg, x, y);
    


  • ich verwende eigentlich immer getop_long in einer whileschleife.

    struct option param_options[] =
    {
       {"host",        required_argument, NULL, 'h'},
       {"user",        required_argument, NULL, 'u'},
       {"password",    optional_argument, NULL, 'p'},
       {"port",        required_argument, NULL, 'P'},
       {"socket",      required_argument, NULL, 'S'},
       {0,0,0,0}
    };
    
    char *hostname = NULL;
    char *username = NULL;
    char *password = NULL;
    unsigned int port = 0;
    char *socketname = NULL;
    
    int c, i = 0,optionindex = 0;
    
     while((c = getopt_long(argc,argv, "h:p::u:P:S:",
                 param_options, &optionindex)) != EOF)
       {
          switch(c)
          {
            case 'h':
                hostname = optarg;
                break;
            case 'u':
                username = optarg;
                break;
            case 'p':
                if (!optarg)
                {
                    password = get_tty_password(NULL);
                }
                else
                {
                    password = optarg;
                }
                break;
            case 'P':
                port = (unsigned int) atoi(optarg);
                break;
            case 'S':
                socketname = optarg;
                break;
          }
       }
    

Anmelden zum Antworten