You are not logged in.

#1 2010-08-12 13:02:34

Google
Member
From: Mountain View, California
Registered: 2010-05-31
Posts: 484
Website

C Programming, command line parsing...

I am using getopt() and a switch to parse my input, as shown over at:

http://www.gnu.org/s/libc/manual/html_n … -of-Getopt

I have read about parsing, but I can't parse something the way I want. I want to have a final variable on the command line.

For example: $programname -a -d 4560

However the 4560 is _not_ related to -a or -d, it is entirely on its own and it must come last. I am not sure how I would 'catch' the argument in a switch, and how I could ensure it's the final argument?

My string const in getopt() is like this: "a:d::"

a requires an argument, -d is optional, but now I need a final integer value that doesn't have a flag, just a number... any ideas?

Offline

#2 2010-08-12 13:20:08

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: C Programming, command line parsing...

Use the standard method of stopping option parsing in any getopt based parser.

$ ./progname -a -d -- 4560

However, this will probably throw an error, as your optstring requires an argument to -d. You may want to rethink your logic to make -d always or never require an argument if provided.

Offline

#3 2010-08-12 16:00:36

Inxsible
Forum Fellow
From: Chicago
Registered: 2008-06-09
Posts: 9,183

Re: C Programming, command line parsing...

Google,
Please don't start multiple threads for the same issue.

https://bbs.archlinux.org/viewtopic.php?id=102721


Forum Rules

There's no such thing as a stupid question, but there sure are a lot of inquisitive idiots !

Offline

#4 2010-08-12 23:17:56

Google
Member
From: Mountain View, California
Registered: 2010-05-31
Posts: 484
Website

Re: C Programming, command line parsing...

I didn't want to start multiple threads, the forum has been very slow and freezing since the update. I hit submit but I never posted the messages but I guess the forum did post it afterall? I didn't notice until now. Sorry!

I have figured out a way to point to the integer using some duct tape style programming. I don't like it because it opens up a possibe seg fault. I can check out -- and see if it works better. Now I am using something on the lines of:

(these variable names are not real, but they express the problem)
(in my a and d switch case)
number = atoi(argv[optind])

yea I know it's really shady but it works. It failes if someone puts no int value after -d, results in a segfault.

I am still trying to impliment something better....

Offline

Board footer

Powered by FluxBB