tags:

views:

80

answers:

3

How do I get the option -10 from command line arguments- "tail -10". getopt function finds '1' character. But how do I access the string "10"?

If this can be done by getopt_long, an example would help. Thanks.

+2  A: 

Unless you intend for -1 to be an option with 0 as its argument, the answer is you don't. getopt is only made for processing options that fit the standard POSIX utilities' option syntax. It may be possible to use GNU getopt_long for this purpose, or you could just write your own argv parser (it's easy).

Edit: Actually I think I misread what you want. If you want - followed by any number to be interpreted as an option with that numeric value, I don't think there's any version of getopt that will work. There's no way you can special-case every single number as an option, and if you simply tell getopt that all of the digits are option characters that take arguments, -123 will be interpreted as a -1 option with an argument of 23 (which is fine, you can interpret it from there), but a lone -1 will cause the next argv element to get eaten as an argument to -1, which is difficult or impossible to recover from.

R..
I don't think getopt_long will do it, it requires `--` in front of the argument
Michael Mrozek
If I remember correctly, `getopt_long` includes a 'long-only' option (or perhaps a separate function `getopt_longonly`?) which accepts either a single `-` or a double `--`.
R..
Thanks. I am tempted to not use the getopt function."-123" through getopt is option: -1 and optarg: NULL. We loose the string "23", its not in optarg. Can I access it any other way?
Ramya
Decided not to use getopt. Thank you.
Ramya
+2  A: 

What is going on here is that c the language comes with absolutely no standard about the proper way to handle command line options.

Moreover, the unix world had no such standard for quite some time ( believe there is a whole section about it in the Unix Haters Handbook (PDF link)).

So, people wrote ad hoc handling mechanisms. These eventually evolved toward a common(ish) standard and getopt was born (at Bell labs). Later we got the GNU getopt and getopt_long. These are not required, however, and some programs still manage things their own way.

But before things settled down (and occasionally after), people added new features to the "usual" way of handling options whenever they seemed like a good idea. Now, it's a pretty good bet that tail will want to have the number of lines adjusted more often than any other feature, so making it easy and few keystrokes to adjust must have seemed like a good idea at the time...

dmckee
A: 

I never did like getopt that much, so I did the usual thing and reinvented the wheel. I call my solution argopt. You can get the source and manual page at http://venalicium.dk/repos/argopt/. It is, I think, much easier to use than getopt.

colding