ricecakebear
ricecakebear

Reputation: 301

How to write log file so that it can be read with notepad in real time for C++

I need a logger for C++. And I found this post Small logger class, which led me to this simple logger http://www.drdobbs.com/cpp/201804215.

It mainly uses the following method to wirte to log file.

FILE* pFile = fopen("application.log", "a");
std::ostringstream os;
os<<"I am a log line."<<std::endl;
fprintf(pFile, "%s", os.str().c_str());
fflush(pFile);

But it doesn't work as I expected. I assume, with the log file open in notepad, each new log line would be showing immediately after fprintf and fflush. But it turned out that I have to close and reopen the file with notepad to see the update.

So is there a way to write log file in C++ that allows reading in real time, which makes the log file resemble win32 console or VS output window? I miss the days when I can dump everything to console.log in Javascript. :)

Thanks.

Upvotes: 4

Views: 2401

Answers (2)

ricecakebear
ricecakebear

Reputation: 301

After the accepted answer from mjs pointed me in the right direction, I google searched "notepad auto refresh" and found this https://www.raymond.cc/blog/monitor-log-or-text-file-changes-in-real-time-with-notepad/.

It provides several options to monitor text file changes in Windows, including Notepad++ and other software specifically designed for monitoring text file changes, with features like keyword filter/highlight and save/load monitoring session.

You might find It interesting if you came across the same problem as mine. Cheers.

Upvotes: 0

mjs
mjs

Reputation: 3004

This is not a problem with your code, this is an issue with Notepad. Notepad does not automatically check for changes in the file you have open.

Instead, you should use a tool that does, for instance Notepad++, or indeed most editors designed for programmers.

If you have installed cygwin, you could also use tail -f to monitor additions to the log file.

Upvotes: 4

Related Questions