0

I have written some code, which prints a command line help:

int main(int argc, char **argv)

    printf("$ ./porfolio6 --help \n"
      "Usage: ./portfolio6 options [FILENAME]\n"

       " -h --help Dsiplay this usage information.\n"
       " -n --num Display my student number.\n"
       " -c --chars Print number of characters in FILENAME.\n"
       " -w --words Print number of words in FILENAME.\n"
       " -l --lines Print number of lines in FILENAME.\n"
       " -f --file FILENAME Read from file.\n");
}

I would like to know how to make these options actually work. Currently they just printout without doing what the option requires.

@Apoorv @Carl Norum My updated version of the code is like this but I am still having a few problems with getting everything to show up on the terminal as options

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


void print_usage() {
 printf("Usage: ./portfolio6 options [FILENAME] \n");
}

int main(int arg, char *argc[]) {

int opt =0;
int help = -1, num = -1, chars = -1, words = -1, lines = -1, file = -1;

static struct option long_options[] = {

{"help", required_argument, 0, 'h' },
{"num", required_argument, 0, 'n' },
{"chars", required_argument, 0, 'c' },
{"words", required_argument, 0, 'w' },
{"lines", required_argument, 0, 'l' },
{"file", required_argument, 0, 'f' },
};

 int long_index =0;
while((opt= getopt_long(argc, argv,"hncwl:f:",
             long_options, &long_index )) != -1 {

 switch (opt) {
 case 'h' : /* -h or --h */
 help = 1;
 break;

 case 'n' : /* -n or --n */
 num = 1;
 break;

 case 'c' : /* -c or --c */
 chars = 1;
 break;

 case 'w' : /* -w or --w */
 words = 1;
 break;

 case 'l' : /* -l or --l */
 lines = 1;
 break;

 case 'f' : /* -f or --f */
 file = 1;
 break;
 }
}

1 Answers1

2

You're looking for getopt_long(3). There's an example in that man page that covers everything you need to know.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
  • 4
    If this is an answer, as opposed to a comment, perhaps an example would be appropriate. – Tom Fenech Jan 02 '15 at 16:05
  • 1
    @TomFenech then again, providing an example here wouldn't amount to much more than pasting the man page's example, unless it was more thoroughly commented. – SirDarius Jan 02 '15 at 16:08