[英]Redirect stdout back to console
有很多關於將stdout和stderr重定向到文件而不是控制台的文檔。 你如何再次重定向? 下面的代碼顯示了我的意圖,但輸出“stdout只打印到控制台”一次。
我猜我需要獲取控制台輸出緩沖區,將其存儲在某處,將stdout重定向到文件,然后恢復控制台緩沖區?
#pragma warning(disable:4996)
#include <cstdio>
int main()
{
std::printf("stdout is printed to console\n");
if (std::freopen("redir.txt", "w", stdout)) {
std::printf("stdout is redirected to a file\n"); // this is written to redir.txt
std::fclose(stdout);
std::printf("stdout is printed to console\n");
}
getchar();
return 0;
}
感謝上面評論中的文章,我找到了我需要的信息。 dup和dup2功能是我所需要的。 請注意,基於信息, dup和dup2不贊成使用或_dup和_dup2。 工作示例可以在MSDN上找到這里 ,但在下面的情況下復制在未來的鏈接斷開。
// crt_dup.c
// This program uses the variable old to save
// the original stdout. It then opens a new file named
// DataFile and forces stdout to refer to it. Finally, it
// restores stdout to its original state.
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
int main( void )
{
int old;
FILE *DataFile;
old = _dup( 1 ); // "old" now refers to "stdout"
// Note: file descriptor 1 == "stdout"
if( old == -1 )
{
perror( "_dup( 1 ) failure" );
exit( 1 );
}
_write( old, "This goes to stdout first\n", 26 );
if( fopen_s( &DataFile, "data", "w" ) != 0 )
{
puts( "Can't open file 'data'\n" );
exit( 1 );
}
// stdout now refers to file "data"
if( -1 == _dup2( _fileno( DataFile ), 1 ) )
{
perror( "Can't _dup2 stdout" );
exit( 1 );
}
puts( "This goes to file 'data'\n" );
// Flush stdout stream buffer so it goes to correct file
fflush( stdout );
fclose( DataFile );
// Restore original stdout
_dup2( old, 1 );
puts( "This goes to stdout\n" );
puts( "The file 'data' contains:" );
_flushall();
system( "type data" );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.