C++实现可执行文件输入参数执行

  • Overview about command line parameters

    Command-line parameters are passed to a program at runt-time by the OS when the program is requested by another program, such as a command interpreter ("shell") like cmd.exe on WIndows or bash on Linux and OS X.

    The user types a command and the shell calls the OS to run the program.

    The uses for command-line parameters are various, but the main two are:

    1. Modifying program behaviour - command-line parameters can be used to tell a program how you expect it to behave;
    2. Having a program run without user interaction - this is especially useful for programs that are called from scripts or other programs;
  • The command-line

    Adding the ability to parse command-line parameters to a program is very easy. Every C and C++ program has a main function. In a program without the capability to parse its command-line, main is usually defined like this :

    int main()
    

    To see the command-line we must add two parameters to main which are, by convention,named argc (argument count) and argv (argument vector [here, vector refers to an array, not a C++ or Eucilidean vector]).

    argc has the type int and argv usually has the type char** or char* [] (see below). main now looks like this:

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

    argc : tells you how many command-line arguments there were. It is always at least 1, because the first string in argv (argv[0]) is the command used to invoke the program. argv contains the actual command-line arguments as an array of strings, the first of which (as we have already discovered) is the program’s name.

    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        std::cout << argv[0] << std::endl;
        return 0;
    }
    

    This program will print the name of the command you used to run it.

    Earlier it was mentioned that argc contains the number of arguments passed to the program. This is useful as it can tell us when the user hasn’t passed the correct number of arguments, and we can then inform the user of how to run our program:

    #include <iostream>
    
    int main(int argc, char* argv[])
    {
        // check the number of parameters
        if (argc < 2){
            // tell the user how to run the program
            std::cerr <<"Usage:"<<argv[0]<<" NAME"<<std::endl;
         	return 1;
        }
        // print the user's name
        std::cout << argv[0] << " says hello, " << argv[1] << "!" << std::endl;
        return 0;
    }
    
  • References

  1. How to parse command line parameters.

猜你喜欢

转载自blog.csdn.net/The_Time_Runner/article/details/108893346
今日推荐