我现在想要用C++ 打开并读取UTF8编码文件,要求不能乱码
时间: 2023-08-04 19:33:56 浏览: 60
您可以使用C++中的fstream库来打开和读取UTF-8编码文件。下面是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file("test.txt", std::ios::in | std::ios::binary);
if (file.is_open())
{
// 获取文件长度
file.seekg(0, std::ios::end);
int length = file.tellg();
file.seekg(0, std::ios::beg);
// 读取文件内容
char* buffer = new char[length + 1];
file.read(buffer, length);
buffer[length] = '\0';
// 转换编码格式
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide_string = converter.from_bytes(buffer);
// 输出内容
std::wcout << wide_string << std::endl;
// 释放内存
delete[] buffer;
}
else
{
std::cout << "Failed to open file!" << std::endl;
}
return 0;
}
```
在这个示例中,我们首先打开一个UTF-8编码的文件,并读取其内容到一个char数组中。接着,我们使用std::wstring_convert类将char数组中的UTF-8编码转换为宽字符格式,并输出到控制台中。
需要注意的是,我们在使用std::wstring_convert类之前需要包含头文件`<locale>`和`<codecvt>`, 并在编译时需要指定C++11标准或以上。
另外,如果您的文件中包含BOM(Byte Order Mark)头部,需要在打开文件时指定打开方式为`std::ios::binary`,以确保BOM头部不会被误解析。