Reading the command line
int main(int argc, char **argv) is how a program sees its command line. argv[0] is the name it was invoked as, argv[1] onwards are the arguments, and argc counts them all including the name.
Everything in argv is a string, always. A number on the command line arrives as text and has to be converted.
Compare strings with strcmp, which returns 0 when they are equal. argv[1] == "-n" compares two ADDRESSES and is essentially always false — a mistake that compiles cleanly.
Example
if (argc > 1 && strcmp(argv[1], "--help") == 0) {
printf("usage: tool [--help]\n");
return 0;
}Check argc BEFORE reading argv[1], or you read a pointer that is not there.
Your task
Write a tool that counts its arguments and recognises one flag. With -v anywhere in the arguments, print verbose: N where N is the number of arguments that are not the flag. Without it, print quiet: N. Do not count argv[0].
- ·Compare the flag with
strcmp, not with==
Stuck?
Explain it
What does argv[1] == "-v" actually compare?
Where this goes
Project 8 is a real command line tool with flags, arguments and a usage message. This is its argument loop, which is the first thing it asks you to build.
Run uses: ./tool — Check tries several argument lists.
This is a teaching runtime for a subset of C, running in your browser on a 32-bit model machine. It reports mistakes a real compiler lets through — reading uninitialised memory, running off an array, signed overflow — and it is not the compiler your project uses.
Press Run to see what your program does, or Check when you think it is right. Everything runs here in your browser.