Pass multiple arguments in C command line - c

How am i able to pass multiple arguments in a C program like this, using different switches
program -d <argument1> -p <argument2>
I'm using getopt to enable me to pass arguments.
int main(int argc, char **argv)
{
while(1)
{
unsigned int c = getopt(argc, argv, "-dD:hHgGp:");
if( c == -1 ) break;
switch( c )
{
case 'D':
case 'd':
printf("\nd=");
strcpy(D,optarg);
printf(D);
break;
case 'g':
case 'G':
printf("g");
break;
case 'p':
printf("\nPath=");
strcpy(pathFile,optarg);
printf(pathFile);
break;
case 'H':
case 'h':
usage(); //For help
return 0;
default:
return 0;
}
}
}
EDIT: The code here is a dummy code which I use for testing. It returns the argument that is passed as a string.

Is it just a case of you forgetting the “:” after the “d” in getopt arguments?
unsigned int c = getopt(argc, argv, "-d:D:hHgGp:");

It seems rather odd to write this:
while (1)
{
unsigned int c = getopt(argc, argv, "-dD:hHgGp:");
if( c == -1 ) break;
The return value of getopt() is an int; why would you save it in an unsigned int?
int opt;
while ((opt = getopt(argc, argv, "-dD:hHgGp:")) != -1)
{
switch (opt)
{
case ...
}
}
If you're going to make options case-insensitive (not a good idea, IMO), then be consistent about it and handle P: too. Also, as first noted by kmkaplan's answer, you have D: and d being handled by the same switch; they should both be followed by a colon for sanity's sake: "-d:D:hHgGp:P:" would at least be self-consistent.
Also, under most circumstances, you don't need to copy the argument string (optarg) anywhere; you simply save a pointer to its current value in a convenient variable. If you do copy the argument string, you must check the length of the argument to ensure you are not overflowing buffers.
The first character of the option string is not normally a dash; it isn't a standard behaviour. The Mac OS X documentation for getopt() does note that it is a GNU extension and advises against ever starting an option string with a dash (and the option string should only contain a dash for backwards compatibility, not in new code — again, on Mac OS X or BSD). Under GNU getopt(), the leading dash means that non-option arguments are reported as if they were options. As long as you're aware that you're using a GNU getopt() extension, there's no harm in doing so.

Related

Please explain colons within optional arguments and optarg as seen in the code below

All of the code below makes sense with the exception of how it is that colons are being used and optarg function as seen under case 's' and 'f'. I've attempted to google what exactly each means but I get lost in the jungle of computer science language that confuses me.
while ((c = getopt(argc, argv, "Ss:f:")) != -1) { //ask about colons in office hours
switch (c)
{
case 'S':
should_print_file_size = 1;
break;
case 's':
min_file_size = atoi(optarg);
break;
case 'f':
substring = optarg;
break;
default:
printf("Please only use S, s, or f arguments.");
return -1;
}
}
Please help!
I am assuming you mean this getopt in the while:
while ((c = getopt(argc, argv, "Ss:f:")) != -1)
As #Kaylum pointed out in the comments, the getopt manual states the following syntax:
int getopt(int argc, char * const argv[],
const char *optstring);
Where optstring argument is described as:
optstring is a string containing the legitimate option characters. If
such a character is followed by a colon, the option requires an
argument, so getopt() places a pointer to the following text in the
same argv-element, or the text of the following argv-element, in
optarg
So you can see in the following two cases for s and f:
case 's':
min_file_size = atoi(optarg); // <--- case 's' Takes optarg
break;
case 'f':
substring = optarg; // <--- case'f' takes optarg
break;
and from the while you have s: and f:. So imagine it being stated as something like this:
s: <argument> and f: <argument>

Weird issue with getopt and strings

I'm trying to parse some arguments using getopt() like this:
char *fileName = "medit.db";
char c = ' ';
while((c = getopt(argc, argv, "f")) != -1){
switch(c){
case 'f':
fileName = optarg;
printf("%s\n\n", fileName);
break;
}
}
The thing is when I go to the command line and write
./server -f test
It just gives me a null result but if I write it like this
./server -ftest
All together it works just fine.
Any reason why this code wouldn't work like it intended?
EDIT: As an experiment I tried to put the colon like this f: It works as intended.. Can anyone explain this?
Just like getchar, getopt returns an int. Pretty much everything said there applies here too.
Prototype from getopt(3):
int getopt(int argc, char * const argv[], const char *optstring);
To declare f as requiring an argument:
If such a character is followed by a colon, the option requires an argument, so getopt() places a pointer to the following text in the same argv-element, or the text of the following argv-element, in optarg.
I.e. the format is:
int c = ' ';
while((c = getopt(argc, argv, "f:")) != -1) {
switch(c){
case 'f':
fileName = optarg;
printf("%s\n\n", fileName);
break;
}
}
You need to put two colons AND you need to stop assigning optarg to fileName when an arg is not provided:
getopt(argc, argv, "f::")
case 'f':
if (optarg)//CHECK FIRST
fileName = optarg;
printf("%s\n\n", fileName);
break;
optstring is a string containing the legitimate option characters. If
such a character is followed by a colon, the option requires an
argument, so getopt() places a pointer to the following text in the
same argv-element, or the text of the following argv-element, in
optarg. Two colons mean an option takes an optional arg;

c optarg atoi with no args

Consider the following code:
int number;
while((w = getopt(argc, argv, "n:s:")) != -1) {
switch (w){
case 'n': {
opfile->filename = optarg;
}break;
case 's': {
number = atoi(optarg);
}break;
}
}
Now, when I leave both options or the option s blank, for example I start my program with no command line args, then the number variable still gets a random value.
What am I missing here? Some if-statement in the case of s? Specifically, I want to cover the case where the user doesn't assign a specific value/option to s in the command line arguments.
When there is no 's' option passed to the program, the case 's' branch is not executed at all, and nothing else sets number to a value, which means that subsequent reads trigger undefined behavior. (This is potentially much worse than just giving you a random value when you read from it later. It's a must-fix bug.)
But because nothing else touches number, it will be enough to change
int number;
to
int number = 0;
or whatever else you want your default to be.
(By the way, you should really be using strtol instead of atoi, because atoi ignores syntax errors.)

I was writing this code for a pizza delivery system. When run from the command prompt it displayed an error. How should I run it?

I am building this pizza program using command-line arguments and interface. It should return the ingredients from the arguments.
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
char *delivery = "";
int thick = 0;
int count = 0;
char ch;
while(ch = getopt(argc, argv, "d:t") != EOF)
switch(ch)
{
case 'd' :
delivery = optarg;
break;
case 't' :
thick = 1;
break;
default:
fprintf(stderr, "Invalid option : %s", optarg);
return 1;
}
argc -= optind;
argv += optind;
if(thick)
puts("thick crust");
if(delivery[0])
printf("To be delivered %s", delivery);
puts("ingredients :");
for(count = 0; count<argc; count++)
{
puts(argv[count]);
}
return 0;
}
When running this program using command prompt in windows as :
program -d now -t
it was returning an error :
invalid option: now
How should I run this program and why is this error showing?
You've made five mistakes (two important, three less so) and one of the important mistakes is masking the other.
while(ch = getopt(argc, argv, "d:t") != EOF)
Important mistake #1: The operator precedence of = is lower than !=, so this assigns the result of the comparison to ch, not the return value of getopt as you expected. Less important mistake #1: getopt returns −1 when it reaches the end of the options. EOF is not necessarily equal to −1.
You should have written
while ((ch = getopt(argc, argv, "d:t")) != -1)
Now, when invoked as you described, in the first iteration the value returned from getopt will be 'd', which is not equal to EOF (nor to −1), so the value assigned to ch will be the number 1 (also known as Control-A, or U+0001 START OF HEADING). This number is not equal to either 'd' or 't' (the C standard guarantees 0 < 'a' < 'b' < 'c' < 'd' < ... < 'z', so even if we don't assume ASCII, 1 could only ever be equal to 'a') so the default branch of the switch is taken, and we do this:
fprintf(stderr, "Invalid option : %s", optarg);
return 1;
And here is important mistake 2: you should print ch, not optarg, when you get an invalid option. ch is the option; optarg is the argument to the option, if any. If you had printed ch you would have realized that the value in ch was not what you expected it to be.
The other less important mistakes are
char ch;
This should be int ch; Like in a getchar loop, the value returned from getopt when it reaches the end of the arguments is outside the range of char.
fprintf(stderr, "Invalid option : %s", optarg);
printf("To be delivered %s", delivery);
Both of these need a \n at the end of the string to be printed.
In the original form of your question, your code was badly indented, but I suspect that was because you used 4 spaces for a single level of indentation and an 8-space-wide hard TAB for a second level; it is a long-standing bug in the Stack Overflow interface that this kind of code gets mangled when pasted into a question. So it's not your fault. (You should indent with spaces only, though.) The more serious style problem with your code is that some of your single-statement loops have curly braces around them and some of them don't. Whether or not one should put curly braces around single-statement blocks in C is one of the oldest holy wars; I personally think both sides are wrong, but never mind that; the important thing you should learn is, pick one style or the other and stick to it consistently throughout your code.

C - Why does getopt return 255 on linux?

I've been fooling around with getopt (from unistd.h) recently. I wrote some code that worked fine under Windows 7 compiled with gcc from MinGW, while not working under Raspbian Linux on my Raspberry Pi (I compiled them both with gcc, no options; gcc t.c). For some reason getopt returns int 255 or char ÿ when faced with no switches, when really it should return -1.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char t;
opterr = 0;
while ((t = getopt(argc, argv, "a:")) != -1)
switch (t) {
case 'a':
printf("-a with argument %s\n", optarg);
return 0;
case '?':
printf("uknown option\n");
return 1;
default:
/* This is always 255 under linux, and is never reached under windows */
printf("getopt returned int %d (char %c)\n", t, t);
return 2;
}
return 0;
}
One tought I had was that, actually 255 is -1 in unsinged 8-bit arithmetic, so I tried to put an int cast in the while conditional, but that did nothing.
It looks like your system/toolchain defaults to an unsigned char type. That means when getopt() returns -1, it gets converted to 255 and stored in t. Then that 255 gets promoted to int type (staying 255) and compared to -1, which can't ever match.
getopt() returns int, so you should really declare t as int to match, but if you're set on using char, you're going to need to use signed char.
Aside: Since you say you're compiling with gcc, you might also find the -fsigned-char flag helpful if you want this and other char variables in your program to be signed.
Second Aside: You can duplicate the failure by passing the -funsigned-char flag or by changing t to be an unsigned char in your Windows test, if that makes it easier to debug.

Resources