将stdin定向到文件

这篇博客展示了如何在C程序中通过打开文件并使用`dup`或`dup2`系统调用来重定向标准输入(stdin)到指定的磁盘文件,从而实现输入的读取。文中提供了一个简单的代码示例,并提到了一个在线教育资源网站。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将stdin定向到文件
1. close(0),即将标准输入的连接断开
2. open(filename, O_RDONLY)打开一个想连接到stdin上的文件。当前的最低可用文件描述符是0,所以打开的文件将被连接到标准输入上去。这时候任何想从标准输入读取数据的函数都将从次文件中读入。
#include    <stdio.h>
#include    <fcntl.h>

main()
{
    int    fd ;
    char    line[100];

    /* read and print three lines */

    fgets( line, 100, stdin ); printf("%s", line );

    /* redirect input */

    close(0);
    fd = open("/etc/passwd", O_RDONLY);
    if ( fd != 0 ){
        fprintf(stderr,"Could not open data as fd 0\n");
        exit(1);
    }

    /* read and print three lines */

    fgets( line, 100, stdin ); printf("%s", line );
}


第二种方法:
1. fd=open(file),打开stdin将要重定向的文件,这时候文件的描述符不是0,因为0被stdin占据。
2. close(0), 现在0已经空闲
3. dup(fd), 将fd做一个复制,这时候将使用文件描述符0,也就是将打开的文件和文件描述符0也关联起来。这时候文件有两个描述符号,fd和0
4. close(fd), 关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。

  1. #include    <stdio.h>
    #include    <fcntl.h>
    
    /* #define    CLOSE_DUP        /* open, close, dup, close */
    /* #define    USE_DUP2    /* open, dup2, close */
    
    main()
    {
        int    fd ;
        int    newfd;
        char    line[100];
    
        /* read and print three lines */
    
        fgets( line, 100, stdin ); printf("%s", line );
    
        /* redirect input */
        fd = open("data", O_RDONLY);    /* open the disk file    */
    #ifdef CLOSE_DUP
        close(0);
        newfd = dup(fd);        /* copy open fd to 0    */
    #else
        newfd = dup2(fd,0);        /* close 0, dup fd to 0 */
    #endif
        if ( newfd != 0 ){
            fprintf(stderr,"Could not duplicate fd to 0\n");
            exit(1);
        }
        close(fd);            /* close original fd    */
    
        /* read and print three lines */
    
        fgets( line, 100, stdin ); printf("%s", line );
    }

    强烈向大家推荐一个好网站,[url=http://www.51zxw.net/study.asp?vip=9533333][我要自学网][/url],教程由在校老师录制,,有办公类、平 面设计类,室内设计类,机械设计类教程.....让你足不出门,都可以体现学校的专业教育!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值