Search code examples
cgetopt

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


Solution

  • 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");
    }