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?
Outputting data to a log file
It seems awkward. Why not just write to a file, or redirect to file via > when running the app, or using cerr/clog?
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 );
}
}
}
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?
is freopen a good way of doing this or is there a better way?
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:
These redirections also nest, albeit not concurrently, if that was useful for any reason.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement