简体   繁体   中英

Function getopt in C

I have a problem with situation when I don't write parameters, which I would like to be essential.

  while ((choice = getopt(argc, argv, "a:b:")) != -1) {
    switch (choice) {
    case 'a' :
      printf("a %s\n", optarg);
      break;
    case 'b' :
      printf("b %d\n", optarg);
      break;
    case '?' :
      if (optopt == 'a')
        fprintf (stderr, "Option -%c requires an argument.\n", optopt);
      break;
    }
  }

When I write ./a.out -b test I don't see fprintf() message

Assuming you mean printf() when wrting fprintf() :

I might be wrong, but as far as I remember optarg is char * so you should use %s also in your second printf() .

In case you really meant fprintf() please explain why you expect to see it.

because your fprintf is under this condition if (optopt == 'a') which will be false when optopt is 'b'

if (optopt == 'a')
    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;

try

if (optopt == 'a' || optopt == 'b' )
    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;

I think you'll need to track whether or not option -a has been used yourself - getopt() doesn't have a rich enough spec to capture that information. Something like:

int opt_a_found = 0;

while ((choice = getopt(argc, argv, "a:b:")) != -1) {
switch (choice) {
case 'a' :
  opt_a_found = 1;
  printf("a %s\n", optarg);
  break;
case 'b' :
  printf("b %d\n", optarg);
  break;
case '?' :
  if (optopt == 'a')
    fprintf (stderr, "Option -%c requires an argument.\n", optopt);
  break;
}
}

if (!opt_a_found) {
    fprintf (stderr, "Option -a is required.\n");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM