简体   繁体   English

将stdout和stderr重定向到C ++中的文件

[英]Redirecting stdout and stderr to a file in c++

I am trying to redirect stdout and stderr to a log file. 我正在尝试将stdout和stderr重定向到日志文件。

/* Redirecting stderr buffer to stdout */
dup2(fileno(stdout), fileno(stderr));

/* Redirecting stdout buffer to logfile */
    if((LogStream = freopen(LogPath.c_str(), "w", stdout)) == NULL)
    {
            cout << "Failed to redirect console logs\n";
    }   

.
.
. //other code
.
.
fclose(LogStream);
LogStream = freopen (NULL_LOG, "w", stdout);

This is what i am doing. 这就是我在做什么。 But still i am missing out some of the logs. 但是我仍然缺少一些日志。 I came to know that when i executed my application commenting out these lines of code. 我知道执行我的应用程序时,注释掉了这些代码行。 I am dubious about this code snippet. 我对此代码段存疑。 Please provide your feedback on this. 请提供您对此的反馈。

first close stdout and stderr 首先关闭stdout和stderr

close(STDOUT_FILENO);
close(STDERR_FILENO)

open new file to write logs to. 打开要写入日志的新文件。

int file = open( "logfile", O_CREAT | O_RDWR, 0644 );

duplicate the logfile file descriptor to use with stdout and stderr. 复制日志文件文件描述符以与stdout和stderr一起使用。 see man dup2 man dup2

dup2( file, STDOUT_FILENO);
dup2( file, STDERR_FILENO);

I hope above code help you.. 希望以上代码对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM