简体   繁体   中英

Implementing a command-line argument

I have to implement the main function with the following signature:

    int main(int argc, char *argv[])

What is a command-line argument and why don't I need test cases for it? And what do they mean by "signature"? Is it just the function prototype?

And I will definitely edit this question to include my attempt at the solution once I get these things clarified.

I'm confused on what this program essentially does, I can see it returns an integer value, but what does that integer value represent? Also, how would I return an integer value with the arguments specified in the argument list? What do they mean? Thanks for the help!

While this is a terrible question that shows little effort, I feel obligated to help ease your confusion.

Here's a program which prints out it's name ( argv[0] ), and requires at least one argument. If it isn't given at least one argument, it returns 1 to indicate failure. Otherwise, it prints out its arguments and returns 0 to indicate success (to the shell, or whoever started it).

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("Hello World, my name is \"%s\" \n", argv[0]);

    if (argc < 2) {
        printf("I require at least 1 argument! Exiting!\n");
        return 1;  // Indicate failure.
    }


    printf("I was given %d command-line arguments:\n", argc-1);
    for (i=1; i<argc; i++) {
        printf("  [%d] %s\n", i, argv[i]);
    }

    return 0;    // Indicate success
} 

Compile and run that program, things should become more clear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM