the redirection fails while using dup2 in linux system

Viewed 33

The function dup2 really confuses me. The code below can not redirect the printf to files.

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main(int argc, const char* argv[]) {
    int fd = open(argv[1], O_RDWR | O_CREAT, 0644);
    int backup = dup(STDOUT_FILENO);
    int replaced = dup2(fd, STDOUT_FILENO);
    printf("replaced = %d\n", replaced);
    printf("asdsadasdasd\n");
    dup2(backup, STDOUT_FILENO);
    close(fd);
    return 0;
}

while the code below can. I can hardly tell the difference between the 2 versions of code. pls help

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

int main() {
    int fd = open("data.out", O_RDWR | O_CREAT,0666);
    printf("file fd: %d\n", fd);
    int backup = dup(STDOUT_FILENO);
    int replaced = dup2(fd, STDOUT_FILENO);
    printf("duplicated file descriptor: %d\n", replaced);
    printf("haha\n");
    dup2(backup, STDOUT_FILENO);
    close(fd);
    return 0;
}
0 Answers
Related