Sarc Sarc - 4 months ago 42
C Question

Optional getopt function

I am having difficulty making getopt operation optional. Here's a part of my code. It takes in an argument file, which if it is there, it counts the number of characters. If not it counts the stdinput characters.

My question is what optarg gets set to once it is undeclared? And how do I go about making my option -c optional and making this work.

Currently it always read from stdin.

while( (option = getopt(argc, argv, "c::") ) != -1 ) {
switch(option) {
case 'c':
if (optarg == NULL) {
file = stdin;
else {
file = fopen(optarg, "r");
while( (ch = fgetc(file)) != EOF ) {
printf("%d %s\n", count, optarg);

alk alk

Optional arguments to options are not supported by "Standard" (POSIX) getopt(). The use of a double colon "::" is a GNU getopt() extension.

To have getopt() set optarg to an option's "optional" argument use the option on calling the program like this:

program -coptional_argument_to_option_c

However alternatively you might like to take one of the the following approaches:

  • Define -c filename with filename being mandatory. And if -c filename misses just count what is read from stdin.

  • Or define -c with no argument to tell your program what to do (to count here) and additionally define an option to tell your program where to read from like -f filename. If the latter misses read from stdin.