How do I make command-line options override the values in a config file?

So in my pomodoro_curses C app, the code for which you can find on GitHub and which I’ve posted about in the past, I’m testing my interface as I work on how to alert the user that a time period has ended. In testing this feature, which in itself is giving me some trouble, I’m passing command-line options, because the defaults, as seen in the config file, are for long periods of time. In testing, I usually invoke it thus:

make # from the top-level project dir
./bin/pomodoro_curses -b 1 -B 1 -c config.ini -n 1 -p 2 -s 1

Read the code if you want an overview of the flags, as the exact meanings are irrelevant right now.

You can’t see config.ini on GH, but just pretend it were config-sample.ini.

The file specifies breaks longer than a minute. When I invoke the program as above, the options set by -[nps] all work as specified on the command line because they come after -c. But -[bB] do not. I understand that this comes from the way that the getopt loop works in conjunction with how I call the program.

I know that I could get around this by fiddling with the order of options on the command-line, putting -c at the beginning to ensure that the command-line flags override the config file and then documenting that, but is there a better way to do this, in line with Exercise 28, strategy 5 (prevention over documentation, page 166)?

Sure, it’s just a little more involved. You could save all explicit args in another struct and overwrite the final values that possibly come from the file with them after the loop.

Btw. I think you’re doing a great job with your comments. Your code is very easy to understand, not a small feat in C…

Okay, so I worked on it, and I’m pretty certain it works (I hope it does lol, I pushed to main on remote :upside_down_face: Personal project or not, not a bad habit I want to get into). Thank you for the suggestion — it really wasn’t that hard to implement, just hard to come up with from my perspective.

As for your other comment, thank you! I can’t stand bad documentation, as it feels hardly better than no documentation whatsoever. I once used libraries in Python for an important project I was working on; I initially thought the documentation was good, because it was pretty good for explaining what was supposed to happen, until I realized it failed to document various errors, and then I had to go hunt for answers elsewhere. That’s why I keep in mind the importance of docs — you never know who could use your code.

If you find any bugs, of course feel free to open an issue.

1 Like