I am trying using dup2 redirect stdout to another file:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int newfd;
if ((newfd = open("output_file.txt", O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
exit(1);
}
printf("Luke, I am your...\n");
dup2(newfd, 1);
printf("Foobar.\n");
return 0;
}
When the first printf
prints a newline \n
, Luke, I am your...
will be printed to the screen and Foobar
will be written to output_file.txt, if the first printf does not print a new line printf("Luke, I am your...");
, both string will be written to output_file.txt. So seems printf will write the first string to a buffer when there is not a newline(\n
).
What really happens underlying then ?