/* dup2ex.c Jim Plank CS360 Dup lecture Showing how dup2(fd, 1) redirects standard output to the file in fd. */ #include #include #include #include #include int main() { int fd; char *s; fd = open("file4.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666); if (dup2(fd, 1) < 0) { perror("dup2"); exit(1); } printf("Standard output now goes to file4.txt\n"); close(fd); printf("It goes even after we closed file descriptor %d\n", fd); putchar('p'); putchar('u'); putchar('t'); putchar('c'); putchar('h'); putchar('a'); putchar('r'); putchar(' '); putchar('w'); putchar('o'); putchar('r'); putchar('k'); putchar('s'); putchar('\n'); s = "And fwrite\n"; fwrite(s, sizeof(char), strlen(s), stdout); fflush(stdout); s = "And write\n"; write(1, s, strlen(s)); return 0; }