我如何打印的__FILE__扩展到正确的字符串? [英] How do I print the string which __FILE__ expands to correctly?
问题描述
考虑此程序:
#include <stdio.h>
int main() {
printf("%s\n", __FILE__);
return 0;
}
根据文件的名称,这个方案工作的 - 或没有。我现在面临的问题是,我想在一个编码安全的方式来打印当前文件的名称。然而,如果文件中有一些奇怪的字符,不能重新在当前code页面psented $ P $,编译器产生一个警告(理应如此):
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)
我该如何解决呢?我想存储由 __ __ FILE
在例如给出的字符串UTF-16,这样我可以正常打印任何其他系统上运行时(通过将存储UTF-16重$ P $到任何运行时系统采用psentation)。要做到这一点,我需要知道:
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:
- 用于通过
__ __ FILE
指定字符串编码是什么?看来,至少在Windows上,目前系统code页面(在我的情况下,Windows 1252)使用 - 但这只是猜测。这是真的? - 如何存储字符串的UTF-8(或UTF-16)再presentation在编译的时候我的源$ C $ C?
- 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? - How can I store the UTF-8 (or UTF-16) representation of that string in my source code at build time?
我的现实生活中的使用案例:我有一个跟踪当前执行的程序,写入电流源$ C $ C /行号信息到一个文件中的宏。它看起来是这样的:
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__ );
这打破情况下,当前的源文件具有包含不能重新当前code页面psented $ P $字符的名称。
This breaks in case the current source file has a name which contains characters which cannot be represented by the current code page.
推荐答案
使用可以使用标记粘贴运算符,如:
Use can use the token pasting operator, like this:
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
#define WFILE WIDEN(__FILE__)
int main() {
wprintf("%s\n", WFILE);
return 0;
}
这篇关于我如何打印的__FILE__扩展到正确的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!