Fre*_*abe 10 c c++ unicode winapi
考虑这个程序:
#include <stdio.h>
int main() {
printf("%s\n", __FILE__);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据文件的名称,该程序可以工作 - 或不工作.我面临的问题是我想以编码安全的方式打印当前文件的名称.但是,如果文件具有无法在当前代码页中表示的有趣字符,编译器会发出警告(这是正确的):
?????????.c(3) : warning C4566: character represented by universal-character-name '\u043F' cannot be represented in the current code page (1252)
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?我想存储由__FILE__例如UTF-16 给出的字符串,以便我可以在运行时在任何其他系统上正确打印它(通过将存储的UTF-16表示转换为运行时系统使用的任何表示).为此,我需要知道:
__FILE__?看来,至少在Windows上,使用了当前的系统代码页(在我的例子中是Windows-1252) - 但这只是猜测.这是真的?我的真实生活用例:我有一个跟踪当前程序执行的宏,将当前源代码/行号信息写入文件.它看起来像这样:
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__ );
Run Code Online (Sandbox Code Playgroud)
如果当前源文件的名称包含当前代码页无法表示的字符,则会中断此操作.
Han*_*ant 11
使用可以使用令牌粘贴运算符,如下所示:
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define WFILE WIDEN(__FILE__)
int main() {
wprintf("%s\n", WFILE);
return 0;
}
Run Code Online (Sandbox Code Playgroud)