tags:

views:

118

answers:

4

I want to make a program to be called from the command line like this:

myprogram.exe -F/-T FILE/TEXT -W FILE.WAV -P FILE.PHO -A

They are 3 parts:

  • myprogram.exe
  • -F OR -T and the File or text
  • -W FILE -P FILE and -A (At least one, up to 3, in any order (or not, if it's complicated))

So it can be:

myprogram.exe -T "Text Text, test text" -A

or:

myprogram.exe -F FILENAME -A

or:

myprogram.exe -F FILENAME -P FILENAME -W FILENAME

etc.

-A is one function (needs the text or the file) -W writes a WAV file with the info from the text/file -P does something similar to -W

What is the best way to handle it? Analyzing argv[x] one by one, and deciding with ifs? Something easier?

I am new to programming and using VS2008.

+6  A: 

You can parse them manually or use Boost.Program_options.

avakar
Thanks, I don't know how I can use this kind of libraries, but I will take a look. I have read that is a bit complicated for newbies... a very simple example somewhere? :)
andofor
+2  A: 

Analyizing argv[x] one by one

That's what I would do. Maybe maintain a counter of the current element ...

unsigned int cur = 0;

if (argc <= 1) {
  .. error 
}

if (!strncmp(argv[cur],"-T",2)) {
  .. process
  ++cur;
}

...

for (;cur < argc;++cur) {
   if (!strncmp(argv[cur],"-F",2)) {
      .. process

   }  
   else if ...
}

There are some command line parers out there. Unix has getopt, for example.

Alexander Gessler
A: 

this is already done by others, so I wouldn't spend all your time on it if I were you. Look at Boost's ProgramOptions for example.

stijn
I'll do it, but I have read that is a bit complicated for newbies...
andofor
+1  A: 

I'd use getopt if you can: it's simple enough. It'll handle combined options too (like in ls -lt instead of ls -l -t) and it handles options with arguments as well, and the order in which they appear also doesn't matter. All this makes it "standard" to people used to command line arguments (normally order of options is irrelevant, except when giving contradictory options...).

Henno Brandsma