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 "); 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 }