C++ wclog

The wclog object in C++ is an object of class wostream. It is associated with the standard C error output stream stderr.

Difference between clog and wclog

clog users char(narrow character) as character type. It can be used for ASCII and ANSI characters.

For internationalization, we need Unicode strings which do not fit in char. wclog uses wchar_t(wide character) and usable for Unicode characters.

Difference between wcerr and wclog

wclog and wcerr, both are associated with stderr, but it differs from wcerr in the sense that the streams in wclog are buffered and not automatically tied with wcout.

Buffered output is more efficient than unbuffered output. In the case of buffered output, all the output is saved into a variable and written to disk all at once. For unbuffered output, we have to keep writing to disk.

Buffered output isn't preferred for critical errors. In case of system crash, there can come a situation where the output was still in buffer and wasn't written to disk and the error message cannot be retrieved. We cannot afford to lose error data in case of system crash so we keep writing the critical errors to disc even though it is slower.

wclog is commonly used for logging purposes. For non-critical event logging, efficiency is more important so wclog is preferred to wcerr.

wclog declaration

extern ostream wclog;

It is defined in <iostream> header file.

The wclog object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. wclog is not tied to any other stream.

The "wc" in wclog refers to "wide character", hence wclog means "wide character log". The

wclog object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:

wclog << varName;

or

wclog << "Some String";

The extraction operator can be used more than once with a combination of variables, strings and manipulators (like endl):

wclog << var1 << "Some String" << var2 << endl;

Example : How wclog works?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	char fileName[] = "data.txt";
	wifstream infile(fileName);
	
	if(infile)
		wcout << infile.rdbuf(); 
	else
		wclog << L"Error while opening the file " << fileName <<endl; 
      return 0;
}

When you run the program, a possible output will be [if there is error in opening the file]:

Error while opening the file data.txt

Check these related library functions as well: