Jump to content
  • Advertisement
Sign in to follow this  
lukesmith123

Outputting data to a log file

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

If you intended to correct an error in the post then please contact us.

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 this post


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

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!