My code is as follows:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(int argc, char *argv)
{
int fd;
int copy_stdout;
char *msg = "a test message for redirect stdout";
fd = open("test", O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
copy_stdout = dup(STDOUT_FILENO);
dup2(fd, STDOUT_FILENO);
close(fd);
write(STDOUT_FILENO, msg, strlen(msg));
dup2(copy_stdout, STDOUT_FILENO);
printf("%s\n", msg);
return 0;
}
If I replace the string write(STDOUT_FILENO, msg, strlen(msg))with printf("%s\n", msg), the program cannot redirect stdoutto the file test, what is the reason for this?
source
share