我正在尝试使用ICU4C和msvc11在Windows上读取UTF-8编码的文件.我需要确定缓冲区的大小来构建一个UnicodeString。由于在ICU4C API中没有类似file的函数,所以我想我可以使用一个底层C文件:
#include <unicode/ustdio.h>
#include <stdio.h>
/*...*/
UFILE *in = u_fopen("utfICUfseek.txt", "r", NULL, "UTF-8");
FILE* inFile = u_fgetfile(in);
fseek(inFile, 0, SEEK_END); /* Access violation here */
int size = ftell(inFile);
auto uChArr = new UChar[size];此代码有两个问题:
所以问题是:
编辑:这是可能的解决方案(在msvc11和gcc 4.8.1上测试),基于第一个答案和C++11标准。国际标准化组织,IEC,14882,2011年的几件事:
因此,要使这种可移植性适用于实现定义的char大小为1字节=8位(不知道哪里不正确)的平台,我们可以使用未格式化的输入操作将Unicode字符读入字符:
std::ifstream is;
is.open("utfICUfSeek.txt");
is.seekg(0, is.end);
int strSize = is.tellg();
auto inputCStr = new char[strSize + 1];
inputCStr[strSize] = '\0'; //add null-character at the end
is.seekg(0, is.beg);
is.read(inputCStr, strSize);
is.seekg(0, is.beg);
UnicodeString uStr = UnicodeString::fromUTF8(inputCStr);
is.close();困扰我的是,我必须为字符创建一个额外的缓冲区,然后才能将它们转换为所需的UnicodeString。
发布于 2013-07-08 03:37:38
这是使用ICU的另一种选择。
使用标准的std::fstream,您可以将文件的整个/部分读入标准的std::string中,然后使用具有unicode感知的迭代器对其进行迭代。http://code.google.com/p/utf-iter/
std::string get_file_contents(const char *filename)
{
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.reserve(in.tellg());
in.seekg(0, std::ios::beg);
contents.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
return(contents);
}
throw(errno);
}然后在你的代码中
std::string myString = get_file_contents( "foobar" );
unicode::iterator< std::string, unicode::utf8 /* or utf16/32 */ > iter = myString.begin();
while ( iter != myString.end() )
{
...
++iter;
}发布于 2014-08-29 16:50:19
好吧,如果您想一次读取整个文件进行某种后处理,在这种情况下,icu::UnicodeString并不是最好的容器…
#include <iostream>
#include <fstream>
#include <sstream>
int main()
{
std::ifstream in( "utfICUfSeek.txt" );
std::stringstream buffer;
buffer << in.rdbuf();
in.close();
// ...
return 0;
}...or你真正想要的是读进icu::UnicodeString,就像读到任何其他字符串对象一样,但是却走了很远的路……
#include <iostream>
#include <fstream>
#include <unicode/unistr.h>
#include <unicode/ustream.h>
int main()
{
std::ifstream in( "utfICUfSeek.txt" );
icu::UnicodeString uStr;
in >> uStr;
// ...
in.close();
return 0;
}...or我完全想不起你真正的问题是什么。;)
https://stackoverflow.com/questions/17511783
复制相似问题