You don't actually do anything with stderr
so it's status and buffering is unchanged. All you do is change the underlying file descriptor (if the open
call doesn't fail of course).
The same behavior can be had by saving the returned file descriptor from open
and using dup
, or dup2
if you don't close the old file descriptor. I would actually recommend using dup2
instead, as it's more explicit and easier to follow what's happening:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
int fd = open( "newfile.txt", O_WRONLY | O_CREAT | O_TRUNC, 0600 );
if (fd == -1) {
perror("open");
return EXIT_FAILURE;
}
if (dup2(STDERR_FILENO, fd) == -1) {
perror("dup2");
return EXIT_FAILURE;
}
fprintf(stderr, "This is in the text file!");
return EXIT_SUCCESS;
}