C language-enter the file name in the command line and print the File Content
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, enter the following at the command line
/ *
./test arg_1 arg_2
* /
#The results are 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;
}