freopen not writing to the specified file

梦想与她 提交于 2019-12-24 02:16:56

问题


I am trying to redirect output of stdout and stderr using a file. I am using freopen and it creates the file in the correct directory but the file is blank. When I comment out the code to redirect the stdout and stderr - the output shows up on the console.

Here is the code:

freopen(stderrStr.c_str(), "a+", stderr); //where stderrStr and stdoutStr are the path/file name
freopen(stdoutStr.c_str(), "a+", stdout);

fclose(stdout); 
fclose(stderr);

I have placed a printf("I WORK") in main and without the the suppressant it outputs but wont write to the file.


回答1:


In order to do what you are trying to do I use dup2(2).

Simply open(2) two files fd1 and fd2 and then use dup2(fd1, 1) for stdout and dup2(fd2, 2) for stderr.

The OS (libc, loader or kernel, not sure which) sets up 3 open file descriptors before the entry of main:

0 : stdin pipe
1 : stdout pipe
2 : stderr pipe

and from the docs of dup2:

dup2(int oldfd, int newfd) makes newfd be the copy of oldfd, closing newfd first if necessary

so the two dup2 calls replace 1 and 2 with your open files. So after when your process calls write(2) (the syscall all output routines such as printf and cout call) to fd 1 or fd 2 the data will be written to your files rather than to the pipes setup by the OS

man page note:

man pages come in chapters. the notation foo(N) means the man page of name "foo" in chapter N. To open foo(N) type:

$ man N foo

for example to open write(2) type:

$ man 2 write


来源:https://stackoverflow.com/questions/9914907/freopen-not-writing-to-the-specified-file

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