在c中重定向标准输出,然后重置标准输出

Dav*_*vid 6 c unistd.h fcntl

我正在尝试使用C中的重定向将输入重定向到一个文件,然后将标准输出设置回打印到屏幕.有人能告诉我这段代码有什么问题吗?

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

int main(int argc, char** argv) {
    //create file "test" if it doesn't exist and open for writing setting permissions to 777
    int file = open("test", O_CREAT | O_WRONLY, 0777);
    //create another file handle for output
    int current_out = dup(1);

    printf("this will be printed to the screen\n");

    if(dup2(file, 1) < 0) {
        fprintf(stderr, "couldn't redirect output\n");
        return 1;
    }

    printf("this will be printed to the file\n");

    if(dup2(current_out, file) < 0) {
        fprintf(stderr, "couldn't reset output\n");
        return 1;
    }

    printf("and this will be printed to the screen again\n");

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 3

您的第二个dup2调用是错误的,替换为:

if (dup2(current_out, 1) < 0) {
Run Code Online (Sandbox Code Playgroud)