I've never really needed to handle command line arguments in FLTK
before because there's always been some menu option or config file.
I was pleasantly surprised at how easy it is once you've managed
to grok the docs, and decided to post this simple example.

Note that the standard Fl::arg() and Fl::args() do not handle
"option=value" but only "option separateValue" so you would have
to code that up yourself, plus any validation of the arguments.

Tested with 1.1.10 and 1.3.x on Linux only.

Enjoy
D.

/*
 * example program: decoding additional command line arguments
 * save as file.cxx and build using 'fltk-config --compile file.cxx'
 */

#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Window.H>
#include "stdio.h"
#include "string.h"

int helpFlag = 0;
char *optionString = 0;

int arg(int argc, char **argv, int &i)
{
  if (strcmp("-h", argv[i]) == 0 || strcmp("--help", argv[i]) == 0) {
    helpFlag = 1;
    i += 1;
    return 1;
  }
  if (strcmp("-o", argv[i]) == 0 || strcmp("--option", argv[i]) == 0) {
    if (i < argc-1 && argv[i+1] != 0) {
      optionString = argv[i+1];
      i += 2;
      return 2;
    }
  }
  return 0;
}

int main(int argc, char** argv)
{
  int i = 1;
  if (Fl::args(argc, argv, i, arg) < argc)
    // note the concatenated strings to give a single format string!
    Fl::fatal("error: unknown option: %s\n"
              "usage: %s [options]\n"
              " -h | --help     : print extended help message\n"
              " -o | --option # : example option with parameter\n"
              " plus standard fltk options\n",
              argv[i], argv[0]);
  if (helpFlag)
    Fl::fatal("usage: %s [options]\n"
              " -h | --help     : print extended help message\n"
              " -o | --option # : example option with parameter\n"
              " plus standard fltk options:\n"
              "%s\n",
              argv[0], Fl::help);

  Fl_Window* mainWin = new Fl_Window(300, 200);
  Fl_Box* textBox = new Fl_Box(0, 0, 300, 200);
  if (optionString != 0)
    textBox->label(optionString);
  mainWin->show(argc, argv);
  return Fl::run();
}

_______________________________________________
fltk mailing list
[email protected]
http://lists.easysw.com/mailman/listinfo/fltk

Reply via email to