簡體   English   中英

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

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

我正在嘗試將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);

這就是我在做什么。 但是我仍然缺少一些日志。 我知道執行我的應用程序時,注釋掉了這些代碼行。 我對此代碼段存疑。 請提供您對此的反饋。

首先關閉stdout和stderr

close(STDOUT_FILENO);
close(STDERR_FILENO)

打開要寫入日志的新文件。

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

復制日志文件文件描述符以與stdout和stderr一起使用。 man dup2

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

希望以上代碼對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM