Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static ofstream will create a file but never write to it?

Tags:

c++

winapi

I have a function that writes some data to a file:

void log(const std::string& data) 
{
    std::ofstream out_file{ "data.txt", std::ofstream::app };
    out_file << data;
}

This works perfectly fine. However, the second I change the out_file declaration to static, it will create the data.txt file, but it will never actually write any data to it.

No exceptions will ever be thrown, yet the file will always remain empty even when the log function is called several times. If I remove static, the logging function will work normally and write to the file.

This function is being called inside a low level keyboard hook callback. MSDN states that: This hook is called in the context of the thread that installed it. so it shouldn't be a thread related issue.

like image 936
Michael Smith Avatar asked Oct 14 '25 03:10

Michael Smith


1 Answers

The issue was the proper destruction of the global object that was not guaranteed. By adding the following to my code:

out_file << data << std::flush;

It all works as expected.

like image 191
Michael Smith Avatar answered Oct 21 '25 03:10

Michael Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!