← Exercises|

Reading the command line

Prev
Write14 of 14 · about 9 min

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?

Not graded — this is for you.

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.