Establishing via code whether console should be saved to a file (and the name of such file)

I know that when a program is executed in the console, one can specify an output file where the console can be saved. For instance, in Windows:

C:\>myprogram.exe > output.txt

However, is there a way to establish via code, i.e. programatically: 1) whether the console should be saved to a file; and 2) the name of the file to which the output should be saved, if any.

I know that I can of course use fprint or std::cout to print each string to a file the same I can do to the console. But for performance sake, I would like to know if it is possible to establish via code that the entire console should be saved to a file.

2 answers

  • answered 2017-06-17 19:10 Neil Butterworth

    Yes, you can write code like this:

      int main( int argc, char * argv[] ) {
          if ( argc > 1 ) {
             // there is a filename on the command line
             ofstream ofs( argv[1] );       // open named file
             // do something with ofs
          }
          else {
              // do something with standard output
          }
      }
    

  • answered 2017-06-17 19:10 j123b567

    You can use dup2 function (in windows _dup2). It can solve the problem to log to the console exclusively or log to the file exclusively. This is not a solution to log to both.

    You can use some logging library (log4cxx, log4cpp, Boost.Log, QDebug, etc.) They should have abilities you need - e.g. log to both console and file.

    Solution with dup2/_dup2:

    You can open new file, then call dup2 to exchange stdout with that opened file. It can work with c++ streams but I did not try it.

    Relevant part of Microsoft example (all checks removed, pleas se original example. I don't have Windows so I can't verify it.)

    #include <stdlib.h>  
    #include <stdio.h>  
    #include <io.h>  
    
    int main(int argc, char ** argv) {
        FILE *DataFile;
        fopen_s( &DataFile, "data", "w" ); // open file "data" for writing
        _dup2( _fileno( DataFile ), 1 ); // exchange "standard output/console" with file "data"
    
        printf("this goes to 'data' file'\r\n"); // print to standard output, but it will be saved to "data" file
    
        fflush( stdout );  
        fclose( DataFile );
    }
    

    Complete linux verified and working C++ example

    #include <stdlib.h>  
    #include <stdio.h>  
    #include <unistd.h>
    
    #include <iostream>
    
    int main(int argc, char ** argv) {
        FILE *DataFile;
        DataFile = fopen( "data", "w" ); // open file "data" for writing
        dup2( fileno( DataFile ), 1 ); // exchange "standard output/console" with file "data"
    
        std::cout << "this goes to 'data' file from c++" << std::endl;
    
        fflush( stdout );  
        fclose( DataFile );
    }