Introduction
XGetoptCS
is a port of my C++ XGetopt to C#. XGetoptCS
is modeled after the Unix getopt()
function. The basic idea is that you call the XGetoptCS
method Getopt()
in a loop like this:
static int Main(string[] args)
{
char c;
XGetopt go = new XGetopt();
while ((c = go.Getopt(args.Length, args, "aBn:")) != '\0')
{
switch (c)
{
case 'a':
Console.WriteLine("option -a");
break;
case 'B':
Console.WriteLine("option -B");
break;
case 'n':
Console.WriteLine("option -n with arg '{0}'", go.Optarg);
break;
case '?':
Console.WriteLine("illegal option or missing arg");
return 1;
}
}
if (go.Optarg != string.Empty)
Console.WriteLine("non-option arg '{0}'", go.Optarg);
...
return 0;
}
Getopt
will continue processing the command line arguments until it hits the end (returns a '\0'
) or finds an illegal option (returns a '?'
). In the above example, the option string "aBn:"
contains the three legal options: -a, -B (options are case sensitive), and -n. There is a colon (:) after the -n option, indicating that it must be followed by a value. This value string may be retrieved by using the Optarg
property. See the XGetopt.cs module header for more details.
XGetoptCS Demo
So here is my version of Getopt()
for C#. Please note it does not have all features of the latest GNU getopt()
- the limitations are documented in the source header. How to use it is pretty straightforward if you are already familiar with Posix or Unix getopt()
.
The demo project provides a sample app that shows how command line is processed:
How To Use
To integrate XGetopt
into your own app, add XGetopt.cs to your project, and add the line:
using XGetoptCS;
to the file where you want to call
Getopt()
. See demo code in
Program.cs for example.
Revision History
Version 1.0 � 2007 June 5
Usage
This software is released into the public domain. You are free to use it in any way you like, except that you may not sell this source code. If you modify it or extend it, please consider posting new code here for everyone to share. This software is provided "as is" with no expressed or implied warranty. I accept no liability for any damage or loss of business that this software may cause.