当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C语言--在命令行输入文件名字并打印文件内容

C语言--在命令行输入文件名字并打印文件内容

2018年10月27日  | 移动技术网IT编程  | 我要评论

涡阳高公,边疆行远方的家全集下载,死神之奔雷若电

c语言中,经常遇到main函数中argc和argv[]这两个参数。argc是argument count的缩写,即参数的个数;argv是argument vector的缩写,即参数列表。argv[0]是程序本身的名字,argv[1]是在命令行中输入的第一个程序的参数,argv[argc]是null,如下所示:

 

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

#将上述代码编译为test可执行文件,在命令行输入如下内容
/*
./test arg_1 arg_2
*/

#执行结果如下:
/*
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)
*/

搞清楚了argc和argv[],我们就可以使用两者通过命令行向程序传送将要处理的文件名参数,代码如下。

 

 

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


 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网