# Outputting data to a log file

This topic is 2257 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am currently outputting infomation to a log file by using the freopen_s function with stdout to get all of the output from cout in a text file.

So at various places in the codebase I can use cout to output some text to the file.

I was just wondering if this is an ok method to create a log file or if there is something wrong with doing it like this?

##### Share on other sites
It seems awkward. Why not just write to a file, or redirect to file via > when running the app, or using cerr/clog?

##### Share on other sites
Could you explain how I could do that?

##### Share on other sites
 void CLog( const char* szMsg, ... ) //Own, custom function { if( g_CLog_bInitialized ) { char szBuffer[512] = { 0 }; va_list vaArgs; FILE* pFile; va_start( vaArgs, szMsg ); _vsnprintf_s( szBuffer, sizeof(szBuffer), szMsg, vaArgs ); va_end( vaArgs ); fopen_s( &pFile, "MyLog.txt", "a+" ); if( pFile ) { fprintf( pFile, "%s", szBuffer ); fclose( pFile ); } } } 

##### Share on other sites
Sorry I'm a little confused by all of this. The reason I was redirecting the stdout to a text file was so that I can call it from any class without needing to keep track of a file or buffer.

is freopen a good way of doing this or is there a better way?

##### Share on other sites
As above, if you just use stdout and friends then the person running your program can decide where they want the output to go by redirecting output as described in the link above. Alternatively, if you make sure to always use e.g. std::clog where appropriate, then you can do something like:

class ScopedStreamRedirect { std::ostream& os; std::streambuf* old_rdbuf; public: ScopedStreamRedirect(std::ostream& os, std::streambuf* rdbuf) : os(os), old_rdbuf(os.rdbuf()) { os.rdbuf(rdbuf); } ~ScopedStreamRedirect() { os.rdbuf(old_rdbuf); } }; // ... int main() { // ... std::ofstream log_file("debug.log"); ScopedStreamRedirect(std::clog, log_file.rdbuf()); // writes to std::clog now end up in file 'debug.log' }

These redirections also nest, albeit not concurrently, if that was useful for any reason.

##### Share on other sites
Ah I understand now, thank you very much!

• 10
• 16
• 14
• 18
• 15