Reputation: 141
Hello I have a project I'm doing and I need my program to run from the command line and be able to read flags and file names that will be used in the program.
This is my current code. It compiles without entering any flags. I don't think my GetArgs does anything. I had help with that part of the code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1024
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
int numInputArgs;
int idx;
void GetArgs (int argc, char **argv){
for (idx = 1; idx < 4; idx++) {
if (strcmp(argv[idx], "-c") == 0) {
printf("Flag -c passed\n");
break;
}
else if (strcmp(argv[idx], "-w") == 0) {
printf("Flag -w passed\n");
break;
}
else if (strcmp(argv[idx], "-l") == 0) {
printf("Flag -l passed\n");
break;
}
else if (strcmp(argv[idx], "-L") == 0) {
printf("Flag -L passed\n");
break;
}
else {
printf("Error: unknown flag\n");
exit(-1);
}
}
}// end GetArgs
void lineWordCount ( ) {
int c, nl, nw, nc, state;
state = OUT; nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if (state == OUT) {
state = IN; ++nw;
}
printf("%d %d %d\n", nl, nw, nc);
}
}// end lineWordCount
int main(int argc, char **argv){
GetArgs(argc, argv);
lineWordCount();
printf("Hello");
//fclose( src );
}
Upvotes: 1
Views: 6673
Reputation: 36650
You can either use a standard function like getopt()
as mentioned by @Joachim, if it is available on your system, or you can code it yourself. If you have a complicated command line syntax, getopt()
might be better suited - if you only need to check for a limited set of flags, it might be easier to code it yourself, for example:
void GetArgs (int argc, char **argv){
int idx = 0;
for (idx = 1; idx < argc; idx++) {
if (strcmp(argv[idx], "-a") == 0) {
printf("Flag -a passed\n");
} else if (strcmp(argv[idx], "-b") == 0) {
printf("Flag -b passed\n");
} else if (strcmp(argv[idx], "-c") == 0) {
printf("Flag -c passed\n");
} else {
printf("Error: unknown flag %s\n");
}
}
}
Upvotes: 4