设为首页 加入收藏

TOP

C语言--在命令行输入文件名字并打印文件内容
2015-07-16 12:04:08 来源: 作者: 【 】 浏览:73
Tags:语言 命令 输入 文件 名字 打印 内容

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


?

?

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇数据结构之---C语言实现二叉树的.. 下一篇C 语言变长数组 struct 中 char d..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: