-2

I wrote a C program that will need to run with seemingly custom flags. I have an executable named "hw3" that I would use ./hw3 in Terminal to run. Now I want my program to take parameters in if you run it using the flags

./hw3 -check

./hw3 -create 3

I already have a functioning code to complete these tasks, how do I create a new flag to run the program with? Better if you can provide some references too.

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
kostaszx
  • 1
  • 1
  • 3

2 Answers2

3

The "flags" are just command line arguments that you get in argv. You can check them yourself or use some suitable library. For a homework probably better and simpler just to check them yourself.

Go through the arguments, check they are valid and do the work based on them.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
1

Use getopt (on linux)

Here's an example:

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

int
main (int argc, char **argv)
{
  int aflag = 0;
  int bflag = 0;
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;

  while ((c = getopt (argc, argv, "abc:")) != -1)
    switch (c)
      {
      case 'a':
        aflag = 1;
        break;
      case 'b':
        bflag = 1;
        break;
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }

  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
          aflag, bflag, cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

Here are some examples showing what this program prints with different combinations of arguments:

% testopt
aflag = 0, bflag = 0, cvalue = (null)

% testopt -a -b
aflag = 1, bflag = 1, cvalue = (null)

% testopt -ab
aflag = 1, bflag = 1, cvalue = (null)

% testopt -c foo
aflag = 0, bflag = 0, cvalue = foo

% testopt -cfoo
aflag = 0, bflag = 0, cvalue = foo

% testopt arg1
aflag = 0, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -a arg1
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument arg1

% testopt -c foo arg1
aflag = 0, bflag = 0, cvalue = foo
Non-option argument arg1

% testopt -a -- -b
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -b

% testopt -a -
aflag = 1, bflag = 0, cvalue = (null)
Non-option argument -
James Cook
  • 7
  • 1
  • 4
OznOg
  • 4,440
  • 2
  • 26
  • 35
  • 1
    As this answer stands, it's far from complete. A minimal example would go a long way to make this answer widely useful. – Vatine Nov 03 '15 at 08:51