C language-enter the file name in the command line and print the File Content

Source: Internet
Author: User

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;
}


 

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.