当前位置:首页 > 操作系统 > Linux

Linux编程 ---- dup函数

dup,dup2,dup3函数

      顾名思义,dup及duplicate的简写,也就是复制的意思。而事实上这几个函数的功能也确实是复制文件描述符。那为什么要复制文件描述符呢?呵呵,我认为是程序员想偷懒,因为这个功能可以进行输入输出重定向。

 

下面这个程序将实现文件复制功能

             1 #include<stdio.h>
 2 #include<sys/types.h>
 3 #include<fcntl.h>
 4 #include<stdlib.h>
 5 #include<sys/stat.h>
 6 #include<unistd.h>
 7 #include<errno.h>
 8 #include<string.h>
 910void err_exit(constchar *msg)
11{
12     fprintf(stderr,"%sn",msg);
13     exit(1);
14}
1516int main(int argc, constchar *argv[])
17{
18if(argc != 3)
19         err_exit("Argument Error!");
20int fdr = open(argv[1],O_RDONLY);
21if(fdr == -1)
22        err_exit(strerror(errno));
23int fdw = open(argv[2],O_CREAT | O_EXCL | O_RDONLY | O_RDWR,0666);
24if(fdw == -1)
25        err_exit(strerror(errno));
26int fd_out = dup(STDOUT_FILENO);//保存标准输出文件描述符27int fd_in = dup(STDIN_FILENO);
2829    dup2(fdw,STDOUT_FILENO);
30    dup2(fdr,STDIN_FILENO);
3132int data;
33while((data = getc(stdin)) != EOF)
34    {
35        putc(data,stdout);
36    }
3738//printf("Hello Hjjn");//这句将写入文件中39    fflush(stdout);
40    close(fdr);
41    close(fdw);
42     dup2(fd_out,STDOUT_FILENO);//恢复标准输出43    dup2(fd_in,STDIN_FILENO);
44     printf("Hello Hjjn");
45return0;
46 }

 

 

 

原文:http://www.cnblogs.com/lighthjj/p/3856068.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐