Strange behaviour when redirecting stdout in C

做~自己de王妃 提交于 2019-12-22 18:39:51

问题


I'm trying to redirect stdout to a file and then restore it back to original in C, but I'm facing the following strange issue - the following piece of code succesfully writes
in stdout
in stdout
in stdout and in file in the respective file which is all OK.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    printf("in stdout \n");
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

However, removing the first row of my main function:

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#define STDOUT 1
int main(int argc, char* argv[]){
    int old_out = dup(STDOUT);
    close(STDOUT);
    int fd = open("./redirected",O_CREAT|O_RDWR|O_TRUNC,0777);
    printf("in file \n");
    close(fd);
    dup(old_out);
    printf("in stdout\n");
    return EXIT_SUCCESS;
}

leads to in file
in stdout
being written on stdout and nothing being written in the file. I wonder how this happened? Thanks for any help.


回答1:


It's a buffering issue. The buffer you write "in file" to isn't flushed before stdout is reinstalled, so the output goes to stdout and not to the file. Adding fflush(stdout); fixed it here.



来源:https://stackoverflow.com/questions/8779356/strange-behaviour-when-redirecting-stdout-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!