1

Ok, so basically I am looking for a number following inputs a and b and I'm searching for c and d without requiring additional info. When I try to do this using getopt, however, my loop never executes. Here is some example code:

int aa = 0;

int av = 0;

int ab = 0;

int bv = 0;

int ac = 0;

int cord = 0;// no c or d = 0, c = 1, d = 2

//flags and a/b value holders

int getoptvalue = 0;

printf("starting getopt\n");

while((getoptvalue = getopt(argc,argv,"cda:b:")) != -1){

printf("inside getopt\n");

  switch(getoptvalue){

  case a:if(aa||ab){

         exit(1);

         }

         else{

         aa = 1;

         av = atoi(optarg);//takes int value following 'a' for storage in av?

         }break;

  case b:if(ab){

         exit(1);

         }

         else{

         ab = 1;

         bv = atoi(optarg);//takes following int value for storage?

         }break;

  case c:if(ac){

         exit(1);

         }

         else{

         ac = 1;//c/d switch

         cord = 1; // showing c was reached

         }break;

  case d:if(ac){

         exit(1);

         }

         else{

         ac = 1;

         cord = 2; //showing d was reached

         }break;

  default: break;

  }

printf("done.\n");

}

When compiled, this code prints:

$prog1 a1 b2 starting getopt done.

It clearly isn't running the loop since it never prints "inside getopt", but I cannot figure out why. Any ideas?

Gopi
  • 19,784
  • 4
  • 24
  • 36
dashiz
  • 41
  • 4

1 Answers1

0

I have changed your code now it looks like this

#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,char* argv[]) {
int aa = 0;

int av = 0;

int ab = 0;

int bv = 0;

int ac = 0;

int cord = 0;// no c or d = 0, c = 1, d = 2

//flags and a/b value holders

int getoptvalue = 0;

printf("starting getopt\n");

while((getoptvalue = getopt(argc,argv,"cda:b:")) != -1){

printf("inside getopt\n");

  switch(getoptvalue){

  case 'a':if(aa||ab){

         exit(1);

         }

         else{

         aa = 1;

         av = atoi(optarg);//takes int value following 'a' for storage in av?

         }break;

  case 'b':if(ab){

         exit(1);

         }

         else{

         ab = 1;

         bv = atoi(optarg);//takes following int value for storage?

         }break;

  case 'c':if(ac){

         exit(1);

         }

         else{

         ac = 1;//c/d switch

         cord = 1; // showing c was reached

         }break;

  case 'd':if(ac){

         exit(1);

         }

         else{

         ac = 1;

         cord = 2; //showing d was reached

         }break;

  default: break;

  }

printf("done.\n");

}
return 0;
}

Now when i compile this code and run as below way

gcc test.c
./a.out -a a -b b
starting getopt
inside getopt
done.
inside getopt
done.
inside getopt
Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222