我正在寻找Mac下的视窗_wfopen()
,你有什么想法吗?
我需要它来移植一个使用wchar*
作为File接口的Windows库。由于这是一个跨平台库,我无法依赖于客户端应用程序如何获取文件路径并将其提供给库。
发布于 2008-11-05 15:07:27
Mac OS X中的POSIX API可用于UTF-8字符串。为了将wchar_t字符串转换为UTF8,可以使用Mac中的CoreFoundation框架。
下面是一个类,它将从wchar_t字符串包装UTF-8生成的字符串。
class Utf8
{
public:
Utf8(const wchar_t* wsz): m_utf8(NULL)
{
// OS X uses 32-bit wchar
const int bytes = wcslen(wsz) * sizeof(wchar_t);
// comp_bLittleEndian is in the lib I use in order to detect PowerPC/Intel
CFStringEncoding encoding = comp_bLittleEndian ? kCFStringEncodingUTF32LE
: kCFStringEncodingUTF32BE;
CFStringRef str = CFStringCreateWithBytesNoCopy(NULL,
(const UInt8*)wsz, bytes,
encoding, false,
kCFAllocatorNull
);
const int bytesUtf8 = CFStringGetMaximumSizeOfFileSystemRepresentation(str);
m_utf8 = new char[bytesUtf8];
CFStringGetFileSystemRepresentation(str, m_utf8, bytesUtf8);
CFRelease(str);
}
~Utf8()
{
if( m_utf8 )
{
delete[] m_utf8;
}
}
public:
operator const char*() const { return m_utf8; }
private:
char* m_utf8;
};
用法:
const wchar_t wsz = L"Here is some Unicode content: éà€œæ";
const Utf8 utf8 = wsz;
FILE* file = fopen(utf8, "r");
这将适用于读取或写入文件。
发布于 2008-08-15 15:26:27
如果你使用的是Cocoa,那么使用NSString就相当简单了。只需使用-initWithBytes:length:encoding:(或者可能是-initWithCString:encoding:)加载UTF16数据,然后通过对结果调用UTF8String来获得UTF8版本。然后,只需使用新的UTF8字符串作为参数来调用fopen。
你绝对可以用UTF-8字符串来调用fopen,不管是哪种语言--不过在OSX上用C++是无能为力的--对不起。
https://stackoverflow.com/questions/12319
复制相似问题