Question

I tried to redirect standart output (cout) to a file, for debugging purposes

std::ofstream traceFile;
traceFile.open("c:/path/file.txt");
std::streambuf* fileBuff = traceFile.rdbuf();

std::cout.rdbuf(fileBuff);

std::cout << std::unitbuff;

std::cout << "disk is written\n";

But calling cout from a new thread make the code stuck on a mutex. (xmtx.c 39: _Mtxlock()).

Have you got an idea, how i could solve it?

Thank you

Was it helpful?

Solution

This example works fine for me, whilst your test case doesn't. On my machine your code seemed to double free the streambuf from the file, whereas this example swaps it back before the destructors are called.

OTHER TIPS

May be you need to reset cout's streambuf to original.

std::ofstream traceFile;
traceFile.open("c:/path/file.txt");
std::streambuf* fileBuff = traceFile.rdbuf(), *origBuf;

origBuf = cout.rdbuf(); //Save cout's StreamBuf pointer
std::cout.rdbuf(fileBuff); //Set cout's StreamBuf to file's StreamBuf pointer

std::cout << std::unitbuff;

std::cout << "disk is written\n";
cout.rdbuf(origBuf);  //Reset cout's StreamBuf back to original

Also, writing into same file by multiple threads concurrently may not be allowed. That may be reason for the failure of acquisition of mutex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top