Question

hello i am writing a program that takes in multiple options from the command line in c. these are some of the options:

-l   counts number of lines in file
-w   counts words in file
-c   counts characters in file

so to make them work, you could do:

./program -l file.txt
./program -w file.txt
./program -c file.txt

however i want to combine them so that multiple options still do as they should. e.g.:

./program -lwc file.txt

will count lines, words, AND files,

./program -lw file.txt

will count lines AND words,

./program -cl file.txt

will count characters AND lines, etc. i just cant figure out how to do this. this is my code for the arguments:

while ( ( c = getopt( argc, argv, "c:w:l:" ) ) != -1 ) { /* get options */
    switch ( c ) {
        case 'c':
            cflag = 1;
            break;
        case 'w':
            wflag = 2;
            break;
        case 'l':
            lflag = 3;
            break;
    }   
}

is it simply changing options around but it still doesnt work. with the code i have now, combining two options results in a segment fault. any help is appreciated

Was it helpful?

Solution

As Jens Gustedt said: remove the colons from the options to make them not take an argument. Then, when option-processing is done (i.e. getopt returned -1), check if optind is less than argc meaning there was an extra argument (your file-name). Like this:

/* after the while-loop */
if(optind < argc){
    fileName = argv[optind];
    optind++;
}else{
    perror("No file specified");
    return -1;
}

When getopt is done optind points to the first entry in argv that wasn't processed by getopt.

OTHER TIPS

The : in the getopt format are for options with arguments. Delete them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top