r/C_Programming • u/Specialist-Signal598 • Jul 04 '26
Question Is this a good way of implementing an optional command line argument?
I'm very new to C so this might be an obvious problem to solve, but this is my way of checking for an optional command line argument, and changing mode based on that. Is this a safe solution?
int mode = 0; // default mode 0: relative pathing; 1 is exact pathing
int force = 0; // default force 0: dont overwrite; 1 to force writing
if (argv[1] == NULL || argv[2] == NULL) {
printf("mv: expected 2 arguments, \"mv [source] [dest]\"");
return 1;
}
if (strcmp(argv[1], "-f") == 0) {
char ch;
printf("force overwrite? (y/N): ");
fflush(stdout);
ch = getchar();
if (ch == 'y' || ch == 'Y') {
force = 1;
} else {
return 1;
}
}
if (1) {
printf("mode: %i\n", mode);
printf("force: %i\n", force);
printf("argc: %i\n", argc);
for (size_t i = 0; argv[i]; i++) {
printf("%s\n", argv[i]);
}
}
30
u/mykesx Jul 04 '26
Type
man 3 getopt
At the command line
6
u/somewhereAtC Jul 04 '26
A couple of issues. You check that two arguments are missing, but not if only one is missing. Given that -f was entered, you still need two arguments, so the 2-arg check should be conditional on -f present or not (that is, with -f the real arguments shift from 1-2 to 2-3). Using if(1) is redundant; if you need code and/or variables in a special scope then use {} alone, but the if(1) is pretentious.
There is a principal that roughly suggests that any subroutine, including main(), should have a single return statement. The embedded returns don't express that principle.
Others have suggested getopt(), but give this a try on your own. It is a good example of underestimating the task and leads to any number of thready solutions.
4
u/johnwcowan Jul 04 '26
Checking argv[1] and argv[2] before you know how many arguments there are is undefined behavior. You need to check that the value of argc instead: for exactly 2 arguments, argc == 3.
I didn't read past that.
-2
u/tangerinelion Jul 04 '26
argv[i] won't be null...