gpt4 book ai didi

c++ - freopen 不写入指定文件

转载 作者:太空狗 更新时间:2023-10-29 12:06:31 24 4
gpt4 key购买 nike

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

代码如下:

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);

我在 main 中放置了一个 printf("I WORK") 并且没有它输出的抑制剂但不会写入文件。

最佳答案

为了完成您想要做的事情,我使用了 dup2(2)

只需打开(2)两个文件fd1和fd2,然后使用dup2(fd1, 1)作为stdout和dup2(fd2, 2) 用于标准错误。

操作系统(libc、加载器或内核,不确定是哪个)在进入 main 之前设置了 3 个打开的文件描述符:

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

来自 dup2 的文档:

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

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

手册页注释:

手册页以章节的形式出现。符号 foo(N) 表示第 N 章中名为“foo”的手册页。要打开 foo(N),请键入:

$ man N foo

例如打开 write(2) 类型:

$ man 2 write

关于c++ - freopen 不写入指定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9914907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com