Check for specific command-line arguments, and then assign them to variables
Definitely a noob here.
I’m making a simple C program that reads some variables from a file with a simple function.
What I’m trying to accomplish, however, is to allow anyone who calls the program to overwrite the values read from the file, if they specify it in the command line arguments.
I want something like this :
char* filename;
int number;
...
readConfig(filename, number, ...);
if (argc > 1) {
Check if the variables were in the args here, in some way
strcpy(filename, args[??]);
number = atoi(args[??]);
}
I wish this app was called
program -filename="path/to/file.txt" -number=3
I’ve found that I can mark each parameter and match it to each assignable variable and discard the others, but I’m pretty sure there is a more elegant way to do this (maybe with getopts?). )
Thank you very much for your help.
Solution
I found this on geeksforgeeks:
<pre class=”lang-c prettyprint-override”>#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int opt;
put ':' in the starting of the
string so that program can
distinguish between '?' and ':'
while((opt = getopt(argc, argv, ":if:lrx")) != -1)
{
switch(opt)
{
case 'i':
case 'l':
case 'r':
printf("option: %c\n", opt);
break;
case 'f':
printf("filename: %s\n", optarg);
break;
case ':':
printf("option needs a value\n");
break;
case '?':
printf("unknown option: %c\n", optopt);
break;
}
}
optind is for the extra arguments
which are not parsed
for(; optind < argc; optind++){
printf("extra arguments: %s\n", argv[optind]);
}
return 0;
}
Therefore, when you pass -f,
you also need to pass the file name, for example: ./args -f filename
It will say:
$ ./a.out -f file.txt
filename: file.txt
When you pass -i, -l, or –r
, or
-ilr
, it says:
$ ./a.out -ilr
option: i
option: l
option: r
If you pass -f
but don’t have a filename, it will say that the option requires arguments. Anything else will be printed into extra parameters
So, with it, you can add options to getopts, add new cases, do something, for example:
getopts(argc, argv, ":fn:")
The -f file name, -n number, is simple