Linux_C dup()
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 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。