码迷,mamicode.com
首页 > 系统相关 > 详细

Linux_C dup()

时间:2014-11-04 22:26:28      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   for   sp   div   

 1 /*
 2  * stdinredir2.c
 3  * shows two more methods for redirecting standard input
 4  * use #define to set one or the other
 5  */
 6 #include <stdio.h>
 7 #include <fcntl.h>
 8 /*#define CLOSE_DUP  /*open, close, dup, close */
 9 /*#define USE_DUP2   /*opne, dup2, close */
10 int main(void) {
11   int fd, newfd;
12   char line[100];
13   //read and print lines
14   fgets(line, 100, stdin);
15   printf("line: %s", line);
16   
17   fd=open("/home/wiz/wizcode/psh1.c", O_RDONLY);  /* open the disk file */
18 
19   #ifdef CLOSE_DUP
20      close(0);
21      newfd=dup(fd);              /*copy open fd to 0*/
22   #else
23      newfd=dup2(fd,0);           /*close 0, dup fd to 0*/
24   #endif
25   if(newfd!=0){
26     fprintf(stderr, "Could not duplicate fd to 0\n");
27     exit(1);
28   }
29   close(fd);
30   fgets(line, 100, stdin); printf("%s", line);
31   fgets(line, 100, stdin); printf("%s", line);
32   fgets(line, 100, stdin); printf("%s", line);
33   return 0;
34 }

 

Linux_C dup()

标签:style   blog   io   color   ar   os   for   sp   div   

原文地址:http://www.cnblogs.com/wizzhangquan/p/4074889.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!