C Language -- enter the file name in the command line and print the file content; -- command line
In C language programming, argc and argv [] parameters in the main function are often encountered. Argc is the abbreviation of argument count, that is, the number of parameters; argv is the abbreviation of argument vector, that is, the parameter list. Argv [0] is the name of the program, argv [1] is the first program parameter input in the command line, argv [argc] is NULL, as shown below:
# Include "stdio. h "int main (int argc, char * argv []) {printf (" the argc value is % d \ n ", argc); int I; for (I = 0; I <= argc; I ++) {printf ("the argv [% d] value is % s \ n", I, argv [I]);} return 0 ;} # compile the above code into a test executable file and enter the following content in the command line /*. /test arg_1 arg_2 */# the execution result is as follows:/* the argc value is 3 the argv [0] value is. /test_c_0 the argv [1] value is arg_1 the argv [2] value is arg_2 the argv [3] value is (null )*/
After figuring out the argc and argv [], we can use the two to send the file name parameters to be processed to the program through the command line. The Code is as follows.
# Include "stdio. h "int main (int argc, char * argv []) {FILE * fp; int c; fp = fopen (argv [1]," r "); while (c = fgetc (fp ))! = EOF) {printf ("% c", c) ;}fclose (fp); return 0 ;}