Home > other >  Getopt doesn't seem to recognise arguments
Getopt doesn't seem to recognise arguments

Time:12-06

I'm starting a new project in C , I started by creating a function that handles command line arguments using getopt, but it doesn't seem to be working. I'm afraid it is a small mistake, but I've been debugging the code for a while and I still don't understand why it isn't working. The problem is that when running the program it doesn't enter any of the switch cases when I run the program with those flags.

Here's the code:

bool verbose = false;

void commandlinearguments (int argc, char** argv, char** word_file_name, char** GSport) {

    int opt;

    sprintf(*GSport, "%d", 58000 GN);

    while ( opt = getopt(argc, argv, "p:v") != -1 ) {
        switch (opt) {
            case 'p':
                cout << optarg << endl;
                *GSport = optarg;
                break;
            case 'v':
                verbose = true;
                break;
        }
    }
    if ( argv[optind] != NULL ) {
        *word_file_name = argv[optind];
    } else {
        cout << "Word file not specified. Aborting." << endl;
        exit(1);
    }

    return;

}

int main (int argc, char** argv) {

    char* GSport = new char[6];
    char* word_file_name = NULL;

    commandlinearguments(argc, argv, &word_file_name, &GSport);
    cout << word_file_name <<endl;
    cout << GSport << endl;
    cout << verbose << endl;

    return 0;

}

I'm compiling like this:

g   server.cpp -o gs -g

And when I run ./gs wf -p 12345 -v the output is:

wf
58003
0

Anyone can see what I'm doing wrong?

CodePudding user response:

opt = getopt(argc, argv, "p:v") != -1

is the same as

opt = (getopt(argc, argv, "p:v") != -1)

so opt is 0 or 1 depending on whether the result was -1. You probably meant

(opt = getopt(argc, argv, "p:v")) != -1

which assigns the result to opt and then checks whether it was -1.

  • Related