Reputation: 679
I'm writing a program and I want to accept commandline arguments but when I pass any args, it acts as if start is always called. My code is below. Any help is appreciated.
//compile to iservices
// Ilkotech Services - C Core
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s start|shutdown|reload\n",argv[0]);
}
else {
if (strcmp(argv[1],"start") != 0) {
services_start();
}
else if (strcmp(argv[1],"shutdown") != 0) {
services_shutdown();
}
else if (strcmp(argv[1],"reload") != 0) {
services_reload();
}
else {
printf("%s is not a valid argument\n",argv[1]);
printf("Usage: %s start|shutdown|reload\n",argv[0]);
exit(1);
}
}
return 0;
}
int services_start() {
printf("Started.\n");
return 0;
}
int services_shutdown() {
printf("Shutting down!\n");
return 0;
}
int services_reload() {
printf("Reloading services configuration.\n");
return 0;
}
Upvotes: 2
Views: 168
Reputation: 7667
According to the online C++ reference, strcmp() returns zero if the strings are equal. That being the case, your code would be saying, essentially, if the first argument is NOT "start", run services_start().
Upvotes: 0
Reputation: 23699
strcmp
returns 0 if the both strings are equals.
C11 (n1570), § 7.24.4.2 The
strcmp
function
Thestrcmp
function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to bys1
is greater than, equal to, or less than the string pointed to bys2
.
Some programmers used to call the following macro:
#include <string.h>
#define cmp_strings(a, b) (strcmp(a, b) == 0)
Upvotes: 7