C语言重定向?解决思路

C语言重定向?
本帖最后由 GioPna 于 2013-02-05 16:52:12 编辑
输入重定向:<
输出重定向:>

重定向是在命令行中执行的符号,不是存放在程序中。对不对?
给个实例。

------解决方案--------------------

显示x.c的内容
# cat x.c
# include <stdio.h>

int main()
{
    printf("hello\n");

    return 0;
}

执行x
# ./x
hello

执行x,输出重定向至output_file(注意标准输出上就没有显示了)
# ./x > output_file

显示output_file文件的内容
# cat output_file
hello


显示x.c的内容
# cat x.c
# include <stdio.h>

int main()
{
    int a, b;
    scanf("%d%d", &a, &b);
    printf("%d + %d = %d\n", a, b, a + b);

    return 0;
}

执行x,注意"1 2"是输入
# ./x
1 2
1 + 2 = 3

显示input_file的内容
# cat input_file
1 2

执行x,输入重定向至input_file(注意这里就不需要输入"1 2"了)
# ./x < input_file
1 + 2 = 3

输入/输出重定向(>,<)是shell的能力/功能,而shell有这样的能力,是因为系统有dup,dup2这样的API(shell也是用C写的,然后调用API)。