Alex Rivera | Logout

How do I print the string which __FILE__ expands to correctly?

Asked 2010-07-20T14:32:21.723
15

Consider this program:

#include <stdio.h>
int main() {
    printf("%s\n", __FILE__);
    return 0;
}

Depending on the name of the file, this program works - or not. The issue I'm facing is that I'd like to print the name of the current file in an encoding-safe way. However, in case the file has funny characters which cannot be represented in the current code page, the compiler yields a warning (rightfully so):

?????????.c(3) : warning C4566: character represented by universal-character-name '\u043F' cannot be represented in the current code page (1252)

How do I tackle this? I'd like to store the string given by __FILE__ in e.g. UTF-16 so that I can properly print it on any other system at runtime (by converting the stored UTF-16 representation to whatever the runtime system uses). To do so, I need to know:

  1. What encoding is used for the string given by __FILE__? It seems that, at least on Windows, the current system code page (in my case, Windows-1252) is used - but this is just guessing. Is this true?
  2. How can I store the UTF-8 (or UTF-16) representation of that string in my source code at build time?

My real life use case: I have a macro which traces the current program execution, writing the current sourcecode/line number information to a file. It looks like this:

struct LogFile {
    // Write message to file. The file should contain the UTF-8 encoded data!
    void writeMessage( const std::string &msg );
};

// Global function which returns a pointer to the 'active' log file.
LogFile *activeLogFile();

#define TRACE_BEACON activeLogFile()->write( __FILE__ );

This breaks in case the current source file has a name which contains characters which cannot be represented by the current code page.

Edit
Report

1 Answer

-1

In MSVC, you can turn on Unicode and get UTF-16 encoded strings. It's in the project properties somewhere. In addition, you should just use wcout/cout not printf/wprintf. Windows needed Unicode before Unicode existed, so they had a custom multi-byte character encoding, which is the default. However, Windows does support UTF16- it's for example, C#.

#include <iostream>

int main() {
    std::wcout << __WFILE__;
}
answered 2010-07-20T15:39:41.503

Your Answer