程序运行

1 理解test.c, 说出程序功能
2 编译运行程序,提交运行截图
#include    <stdio.h>
#include    <stdlib.h>
#include    <fcntl.h>
#include <unistd.h>
int main()
{
    int    fd ;
    int    newfd;
    char    line[100];

    fgets( line, 100, stdin ); printf("%s", line );//读入一个字符串,并将字符串打印出来
    fgets( line, 100, stdin ); printf("%s", line );
    fgets( line, 100, stdin ); printf("%s", line );

    fd = open("data", O_RDONLY);//    open(filename, O_RDONLY)打开一个想连接到stdin上的文件data

    newfd = dup2(fd,0);    // newfd 与fd 关联的文件关联起来 ;让本来指向标准输出缓冲区的描述符0指向文件data
    
    if ( newfd != 0 ){
        fprintf(stderr,"Could not duplicate fd to 0\n");
        exit(1);//直接退出
    }
    close(fd);//关闭fd,这时候任何想从标准输入读取数据的函数都将从次文件中读入。

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

1、首先采集三次用户输入并打印出来

2、以只读的方式打开data文件,记为fd

3、用newfd关联fd关联的文件并打印用户输入,失败,输出“不能复制fd”

下面两个:

①没有data文件

②有data文件:文件内容为hello,20181217!

 

 

 

posted @ 2020-11-25 16:14  20181217Cindy  阅读(63)  评论(0编辑  收藏  举报