intmain() { int fd, old_stdout; char *filename = "dup2-to-file-output.txt"; // keep the original stdout for restore old_stdout = dup(STDOUT_FILENO); if (old_stdout == -1) { perror("dup failed"); exit(EXIT_FAILURE); } // open the file for writing fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC, 0644); if (fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } // redirect stdout to file if (dup2(fd, STDOUT_FILENO) == -1) { perror("dup2 failed"); exit(EXIT_FAILURE); } close(fd); // close fd, because STDOUT_FILENO is now pointing to it // now printf's output will be written to file printf("This text will be written to %s\n", filename); printf("Another line for testing...\n");
// Remember to flush the buffer otherwise the output will be buffered fflush(stdout); // restore original stdout if (dup2(old_stdout, STDOUT_FILENO) == -1) { perror("dup2 restore failed"); exit(EXIT_FAILURE); } // close the backup descriptor close(old_stdout); // after restore, output to terminal printf("Now back to terminal output\n"); return0; }
编译使用的方法如下所示:
1 2 3 4 5 6 7 8
$ gcc -o linux-dup2-to-file linux-dup2-to-file.c
$ ./linux-dup2-to-file Now back to terminal output
$ cat dup2-to-file-output.txt This text will be written to dup2-to-file-output.txt Another line for testing...
intmain() { int fd, old_stdin; char *filename = "dup2-from-file-input.txt"; char buffer[1024]; // keep the original stdin for restore old_stdin = dup(STDIN_FILENO); if (old_stdin == -1) { perror("dup failed"); exit(EXIT_FAILURE); } // open the file for reading fd = open(filename, O_RDONLY); if (fd == -1) { perror("open failed"); exit(EXIT_FAILURE); } // redirect stdin to file if (dup2(fd, STDIN_FILENO) == -1) { perror("dup2 failed"); exit(EXIT_FAILURE); } close(fd); // close fd, because STDIN_FILENO is now pointing to it // now scanf will read data from file printf("Reading from %s:\n", filename); while (fgets(buffer, sizeof(buffer), stdin) != NULL) { printf("[Read] : %s", buffer); }
fflush(stdin); // restore original stdin if (dup2(old_stdin, STDIN_FILENO) == -1) { perror("dup2 restore failed"); exit(EXIT_FAILURE); } close(old_stdin); // after restore, input from terminal printf("\n\n[Terminal] Enter something: "); strcpy(buffer, "hello world"); printf("\n[Terminal] You entered: %s\n", buffer); fflush(stdout); return0; }
编译使用的方法如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
$ cat dup2-from-file-input.txt Roses are red, Violets are blue, Testing dup2, And stdin too.%
v1.5.2