I wanted to use getopt() to parse arguments supplied at the command line, but I am having trouble with very simple test cases. I have the following code (which is almost, but not entirely identical, to that supplied as an example in the POSIX standard definition).
int main(int argc, char *argv[]) {
int c;
int rmsflg = 0, saflg = 0, errflg = 0;
char *ifile;
char *ofile;
//Parse command line arguments using getopt
while (((c=getopt(argc,argv, ":i:rso:")) != 1) && (errflg == 0)) {
switch(c){
case 'i':
ifile="optarg";
break;
case 'o':
ofile="optarg";
break;
case 'r':
if (saflg)
errflg++;
else {
rmsflg++;
printf("Root Mean Square averaging selected\n");
}
break;
case 's':
if (rmsflg)
errflg++;
else {
saflg++;
printf("Standard Arithmetic averaging selected\n");
}
break;
case ':':
fprintf(stderr,"Option -%c requires an argument\n",optopt);
errflg++;
break;
case '?':
fprintf(stderr,"Option -%c is not a valid option\n",optopt);
errflg++;
break;
default:
fprintf(stderr,"The value of c is %c,\
the option that caused this error is -%c\n",c,optopt);
errflg++;
break;
}
}
if (errflg) {
fprintf(stderr, "usage: xxx\n");
exit(2);
}
return 0;
}
Firstly, when I don't have the default case in there, nothing is output. When I inserted the default case, and make it output the value that c has, I get ?. This is odd for 2 reasons. Firstly, and this is what bothers me most, why doesn't c then match the ? case which was specifically written to match this output, but rather drops through to the default case. Secondly, the output of optopt is (for my input) o. The ? character is only returned if the option supplied does not match any character in optstring.
In the while loop condition you should check the return value of getopt against -1 not 1. Then if you pass the option -? on the command line, it should be recognized.
Related
I don't understand why optopt is zero in my code when an option is recognized but is right when it goes to the '?'case. This is the code:
...
int opt;
while((opt = getopt(argc, argv, OPZIONI))!= -1){
switch(opt){
case 'h':{
printOption();
break;
}
case 'f':{
if(conf->socketname[0] == '\0'){
strncpy(conf->socketname, optarg, strlen(optarg));
}
else printf("Option %c have to been used one time\n", optopt);
break;
}
...
similar code here
...
case '?':{
printf("Option %c not recognised\n", optopt);
break;
}
In else of case f optopt is 0 and it is not printed, but in the case '?' is printed right.
Thank you for your help.
getopt() only sets the optopt variable in the case of an error that makes it return a '?' or ':'. It doesn't set it when it finds an expected option. So using it when getopt() returns 'f' is pointless; it's not going to have any meaningful value in that case.
I am currently working with the function getopt(). I am implementing a program that is similar to the 'ls' command in Unix.
Everything seems to work correctly, however, if say I have a file named "-xyz",and pass the filename as argument, getopt() doesn't treat it as a file/dir.
For example, if i type: ./myprogram -i Makefile -xyz, I expect the function to treat -xyz as a file/dir but instead it tries to treat it as options.
Here is my code:
while((choice = getopt(argc, argv, "ilR")) != -1){
switch(choice) {
case 'i':
opt->option_i = 1;
break;
case 'l':
opt->option_l = 1;
break;
case 'R':
opt->option_R = 1;
break;
default:
exit(1);
}
}
Thank you
I am very new to getopt and I need to get the directory name as an argument by using getopt. It does not work.
The program needs to figure out which argv is the directory so that I can pass the path to a function. I pass either the last command-line argument as a path, if there is a dirname argument, or pass the current working directory to that function.
Please help me on that by providing the correct code fragment:
dt [-h] [-I n] [-L -d -g -i -p -s -t -u | -l] [dirname]
I have tried using optopt but it did not work.
int c;
while( (c = getopt(argc, argv, "hI:Ldgipstul")) != -1){
switch(c){
case 'h':
printf("This is the help message, please read README file for further information");
exit(1);
printf("In the help page\n");
break;
case 'I':
printf("Setting indentation\n");
indentation = atoi(optarg);
printf("Indentation is: %d\n", indentation);
break;
case 'L':
printf("Following symbolic links\n");
break;
case 'd':
//printf("Time of last modification\n");
break;
case 'g':
//printf("Print group id\n");
groupid = groupId(path);
printf("Group Id is: %d\n",groupid);
break;
case 'i':
printf("Print number of links in inode table\n");
int numberlink = numberLinks(path);
printf("number of links: %d\n",numberlink);
break;
case 'p':
printf("Permissions\n");
break;
case 's':
printf("Sizes\n");
break;
case 't':
printf("Information of file\n");
break;
case 'u':
//printf("Print user id\n");
userid = userId(path);
printf("User Id is: %d\n",userid);
break;
case 'l':
printf("Optional one\n");
break;
default:
perror("Not a valid command-line argument");
break;
}
}
When the getopt() loop finishes, the variable optind contains the index of the first non-option argument. That will be the dirname argument. So you can write:
char *directory;
if (optind < argc) {
directory = argv[optind];
} else {
directory = "."; // default to current directory
}
I am attempting to parse a command line argument, which in turn will execute an associated case within a switch statement. When I parse an integer argument (as seen in the code below), the associated case executes correctly. When I attempt to parse a string such as "CPU", I do not get the correct output.
Functioning code (parsing an integer e.g. an argument of 4 gives athe correct output of hello):
#include <stdio.h>
int main(int argc, char *argv[]) {
char execution_mode = atoi (argv[1]);
switch (execution_mode)
{
case (4) :
printf("Hello");
getchar();
break;
case (8) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
My attempt at parsing a string e.g. the argumentCPU:
#include <stdio.h>
int main(int argc, char *argv[]) {
typedef enum MODE { CPU, OPENMP } MODE;
MODE execution_mode = (char)argv[1];
switch (execution_mode)
{
case (CPU) :
printf("Hello");
getchar();
break;
case (OPENMP) :
printf("Goodbye");
getchar();
break;
default:
printf("Error! execution mode is not correct");
getchar();
break;
}
return 0;
}
You cannot convert a string to an enumerate like this. What you're doing is just converting the pointer to the string to char. Which fails.
One alternative (besides comparing first argument with strcmp) to avoid this would be to give a character value to your enumerates:
typedef enum { CPU='C', OPENMP='O' } MODE;
and now you can pick the first letter of the first argument and convert it:
MODE execution_mode = (MODE)argv[1][0];
The letters must be of course all different. And check argc>1 to see if argv[1] is valid, of course
If you want full string match, you have no other choice than using strcmp:
const char *execution_mode = argv[1];
if (strcmp(execution_mode,"CPU")==0)
{
// do something
}
else if (strcmp(execution_mode,"OPENMP")==0)
{
// do something else
}
With the help of the users who have answered this question, I have found a working solution by using strcmp as seen below. I have also added some error checking to ensure enough arguments have been enterred on the command-line.
#include <stdio.h>
int main(int argc, char *argv[]) {
//Ensure there are enough arguments
if (argc < 2)
{
printf("Error: not enough arguments");
exit(1);
}
typedef enum MODE { CPU, OPENMP, CUDA, ALL } MODE;
MODE execution_mode = (MODE)argv[1];
//Compare string with command-line arguments
if (strcmp("CPU", execution_mode) == 0)
{
//selects CPU case
execution_mode = CPU;
}
else if (strcmp("OPENMP", execution_mode) == 0)
{
//selects OPENMP case
execution_mode = OPENMP;
}
else
{
printf("invalid arg");
}
//Switch statement
switch (execution_mode)
{
case (CPU) :
printf("CPU MODE SELECTED");
getchar();
break;
case (OPENMP) :
printf("OPENMP MODE SELECTED");
getchar();
break;
default:
printf("Error: execution mode is not correct");
getchar();
break;
}
return 0;
}
I am writing a simple program which takes the arguments form the user and process them.
I have the arguments in the argv which is two dimensional array. But when i ran the program, i get the garbage value and the segmentation fault error. I have tried with using argc as terminating condition and it works. But i want to do it using the pointer only.
What am doing wrong with pointer here.
#include<stdio.h>
int main( int argc, char *argv[])
{
while (++(*argv))
{
if ( **argv == '-' )
{
switch (*argv[1])
{
default:
printf("Unknown option -%c\n\n", (*argv)[1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", *argv);
}
}
program run as:
./a.out -h -v -d
Thank you
If you want to iterate through program arguments looking for the terminating null pointer, your outer cycle should be
while (*++argv)
not the
while (++*argv) // <- incorrect!
that you have in your code.
Your switch expression is written incorrectly. While your intent is clear, your implementation ignores operator precedence.
This
switch (*argv[1]) { // <- incorrect!
should actually be
switch ((*argv)[1]) {
The previous if
if (**argv == '-')
is fine, but since it is equivalent to
if ((*argv)[0] == '-') // <- better
maybe you should rewrite it that way as well, just for consistency with switch.
Your ultimate problem is operator precedence. Don't try to be clever when it's unnecessary. The * operator does not work as you think it does. I've rewritten your code using [0] instead, and now it works:
#include <stdio.h>
int main(int argc, char *argv[])
{
while ((++argv)[0])
{
if (argv[0][0] == '-' )
{
switch (argv[0][1]) {
default:
printf("Unknown option -%c\n\n", argv[0][1]);
break;
case 'h':
printf("\n option h is found");
break;
case 'v':
printf("option V is found");
break;
case 'd':
printf("\n option d is found");
break;
}
}
printf("\n outside while : %s", argv[0]);
}
}
argv is an array of strings. argv[0] is the program name which in your case is a.out. Your options start from argv[1]. So you need to iterate argv from 1 to argc-1 to get the options.
Also see here: Parsing Program Arguments