Redirection the long way: close, then dup
Redirection the long way: close, then dup
Answer
int fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); close(1); if (dup(fd) != 1) { perror("dup"); return 1; } printf("this goes into out.txt\n");
dup() takes the lowest free slot, and after close(1) that is slot 1 — so the duplicate necessarily becomes standard output. This is exactly what the shell does for the > operator.
S&K 3e ch18 §18.8.1 and ch19 §19.4.2; dup/dup2 semantics per POSIX.1-2024