将标准输出重定向回控制台

时间:2018-10-10 09:59:26

标签: c++ console stdout

关于将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;
}

1 个答案:

答案 0 :(得分:0)

由于上面的评论中的文章,我找到了所需的信息。我需要dup和dup2函数。请注意,基于信息here,不赞成使用dup和dup2或赞成_dup和_dup2。可以在MSDN here上找到一个有效的示例,但是如果将来将来链接断开,在下面也可以复制。

// 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" );
}