Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopt always returns 1

I want to use getopt to get the argument list of my console tool. When I call my tool like below getopt returns always 1 and doesn't mactch any switch/case.

Am I doing something wrong?

  mytool -f farg -d darg

  int 
  main(int argc, char** argv) {
  int c;
  while((c = getopt(argc, argv, "f:d:h") != -1)) {

      switch(c) {
        case'f':
        break;

        default:
        break;
      }
  }
like image 213
Abruzzo Forte e Gentile Avatar asked Feb 13 '23 13:02

Abruzzo Forte e Gentile


1 Answers

while((c = getopt(argc, argv, "f:d:h") != -1))

It works like

c = (getopt(argc, argv, "f:d:h") != -1)

Well, that is 1 always because the result of the comparison is stored to c. In your case the getopt does not return -1. If it returns -1 then c would be 0. The fix is

while((c = getopt(argc, argv, "f:d:h")) != -1)
like image 139
Sakthi Kumar Avatar answered Feb 16 '23 01:02

Sakthi Kumar