freopen不写入指定的文件 [英] freopen not writing to the specified file

查看:162
本文介绍了freopen不写入指定的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用一个文件重定向stdout和stderr的输出。我使用freopen,它创建在正确的目录中的文件,但文件是空白的。当我注释掉重定向stdout和stderr的代码时,输​​出显示在控制台上。



这里是代码:

  freopen(stderrStr.c_str(),a +,stderr); //其中stderrStr和stdoutStr是路径/文件名
freopen(stdoutStr.c_str(),a +,stdout);

fclose(stdout);
fclose(stderr);

我在main中放了一个printf(I WORK),没有输出的抑制剂不要写入文件。

解决方案

为了做你想做的事,我使用 dup2

只需打开(2)两个文件fd1和fd2,然后使用 dup2(fd1, 1) for stdout和 dup2(fd2,2) for stderr。



输入main之前,OS(libc,loader或kernel,不知道是哪一个)设置了3个打开的文件描述符:

  stdin pipe 
1:stdout pipe
2:stderr pipe

doc2的doc2:


dup2(int oldfd,int newfd)使newfd成为oldfd的副本,必要时关闭newfd


因此,两个dup2调用将打开的文件替换为1和2。因此,当进程调用 write(2)(系统调用所有输出例程,如printf和cout调用)到fd 1或fd 2时,数据将被写入文件而不是管道设置由OS



手册页



手册页分为章节。符号 foo(N)表示第N章中名为foo的手册页。要打开foo(N)类型:

  $ man N foo 

例如打开write :

  $ man 2写

$ b b

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.

解决方案

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

这篇关于freopen不写入指定的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆