Redirecting stdout and std::cout to the same place

Started by
2 comments, last by Matt-D 12 years, 6 months ago
My game project is written in C++ but makes use of Lua, which is written in C. My logging functions use std::cout to write messages to a log file, but I'm not able to capture print messages that take place in Lua scripts in the same log file, since the Lua library uses sprintf and the like.

I am using this code to redirect stdout but am receiving warnings from MSVC about freopen being unsafe.

freopen( "file.txt", "w", stdout );

The warnings are not uncommon, and having found a thread about the exact warnings I decided to redirect stdout using a "stream redirection guard" as described in the thread. The redirection works for std::cout but not for stdout. This makes sense to me but I'm not sure how to achieve what I want.

So is it possible to get both pointing to the same stream or file?
Advertisement
It might simply be easier to redefine/overwrite lua's print() function.
Close stdout and stderr, open your new file and then use dup2() to copy the new file descriptor into stdout and stdin.
Have you tried playing with http://www.cplusplus.com/reference/iostream/ios_base/sync_with_stdio/ ?

This topic is closed to new replies.

Advertisement