Skip to content
Advertisement

Check for specific command line arguments and then assign them to variables

Obligatory total noob here.

I am making a simple C program that reads some variables from a file from a simple function. What I’m trying to accomplish, however, is to allow whoever calls the program to override the values read from the file if hey so specify in the command line arguments. I would like to have something like this:

JavaScript

I would like the program to be called as

JavaScript

I figured out I could just tokenize each argument and match it to every assignable variable and discard the others, but I’m pretty sure that there’s a more elegant way to do this (perhaps with getopts?)

Thank you so much for your help.

Advertisement

Answer

I found this on geeksforgeeks:

JavaScript

So, when you pass -f, you need to also pass filename, like: ./args -f filename it will say:

JavaScript

When you pass -i, -l, or -r, or -ilr, it will say:

JavaScript

If you pass -f but without a filename, it will say option needs argument. Anything else will be printed to extra arguments

So, with it, you can add options to getopts, add new case, do a thing, like: getopts(argc, argv, ":fn:") -f filename, -n number, pretty easy

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement