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

在c中重定向标准输出,然后重置标准输出,c,fcntl,unistd.h,C,Fcntl,Unistd.h,我尝试使用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 permissi

我尝试使用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;
}
#包括
#包括
#包括
int main(int argc,字符**argv){
//如果文件“test”不存在,则创建该文件,并打开该文件以将权限设置为777
int file=open(“test”,O|u CREAT | O|u WRONLY,0777);
//为输出创建另一个文件句柄
int current_out=dup(1);
printf(“这将被打印到屏幕上\n”);
if(dup2(文件,1)<0){
fprintf(stderr,“无法重定向输出\n”);
返回1;
}
printf(“这将被打印到文件\n”);
如果(dup2(当前输出,文件)<0){
fprintf(stderr,“无法重置输出\n”);
返回1;
}
printf(“这将再次打印到屏幕上\n”);
返回0;
}

在这一切工作之前,您必须确保做一件事,那就是调用
fflush(stdout)stdout
文件描述符从下面切换出来之前,请执行code>。可能发生的情况是,C标准库正在缓冲您的输出,而没有意识到您正在转换它下面的文件描述符。使用
printf()
编写的数据实际上不会发送到底层文件描述符,直到其缓冲区已满(或程序从
main
返回)

按如下方式插入呼叫:

    fflush(stdout);
    if(dup2(file, 1) < 0) {
fflush(stdout);
if(dup2(文件,1)<0){

在两次调用
dup2()

之前,您的第二次
dup2
调用错误,请替换为:

if (dup2(current_out, 1) < 0) {
if(dup2(当前输出,1)<0){

只需将
dup2(当前输出,文件)
替换为
dup2(当前输出,1)
,事情应该会更好。

我不认为这是OP的问题,但这是一个非常好的建议,当您将stdio与文件描述符io混合使用时,几乎应该始终遵循它。没错,在别人提到之前,我实际上一开始并没有注意到错误的文件描述符。在向终端写入时,stdio输出will可能是行缓冲的,因此在OP尝试将stdout重定向到文件之前,不带
fflush()
的代码可能会工作。这里有一种完全不同的方法来解决相同的问题:。