在Qt中,经常由于文件编码格式导致中文输出乱码,例如:
原因是当前文件的编码格式是
现在把main.cpp保存为:
现在运行程序:
嗯,两个都是乱码,因为还没有设置std::cout的输出格式:
重点来了,有没有在运行时能够判断当前文件是否utf格式:
怎么做到的,用宏定义,下面给出代码:
//假设我们要检测当前源文件是否是 UTF-8 编码
// __FILE__ 是当前源文件的路径
#define _isUTF8 ga.isUTF8File(__FILE__)
/// <summary>
/// 检查字节数据是否符合 UTF-8 编码规则
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
/// 创建时间: 2025-02-12 最后一修改时间:2025-02-12 (摘抄自deepseek)
bool isUTF8(const std::vector<unsigned char>& data);
bool global_c_all::isUTF8(const std::vector<unsigned char>& data)
{
for (size_t i = 0; i < data.size(); ) {
unsigned char ch = data[i];
if ((ch & 0x80) == 0) {
// 1 字节字符(ASCII)
i++;
}
else if ((ch & 0xE0) == 0xC0) {
// 2 字节字符
if (i + 1 >= data.size() || (data[i + 1] & 0xC0) != 0x80) {
return false;
}
i += 2;
}
else if ((ch & 0xF0) == 0xE0) {
// 3 字节字符
if (i + 2 >= data.size() || (data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80) {
return false;
}
i += 3;
}
else if ((ch & 0xF8) == 0xF0) {
// 4 字节字符
if (i + 3 >= data.size() || (data[i + 1] & 0xC0) != 0x80 || (data[i + 2] & 0xC0) != 0x80 || (data[i + 3] & 0xC0) != 0x80) {
return false;
}
i += 4;
}
else {
// 不符合 UTF-8 编码规则
return false;
}
}
return true;
}
/// <summary>
/// 检测文件是否是 UTF-8 编码
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
/// 创建时间: 2025-02-12 最后一修改时间:2025-02-12 (摘抄自deepseek)
bool isUTF8File(const std::string& filePath);
bool global_c_all::isUTF8File(const std::string& filePath)
{
std::ifstream file(filePath, std::ios::binary);
if (!file) {
std::cerr << "无法打开文件: " << filePath << std::endl;
return false;
}
// 读取文件内容
std::vector<unsigned char> data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
// 检查是否是 UTF-8
return isUTF8(data);
}
重点是:
下面,你还可以打印当前源文件:
/// <summary>
/// 读取一个UTF8格式的文件
/// </summary>
/// <param name="sFullPathName"></param>
/// <returns></returns>
/// 创建时间: 2025-02-12 最后一次修改时间:2025-02-12
_StrA global_c_all::readUTF8FileToText(const std::string& sFullPathName)
{
_StrA sResult;
std::ifstream file(sFullPathName, std::ios::binary | std::ios::ate); // 打开文件并定位到末尾
if (!file.is_open()) {
std::cerr << "无法打开文件: " << sFullPathName << std::endl;
return sResult;
}
size_t length = file.tellg(); // 获取文件指针当前位置(即文件长度)
if (length <= 3) return sResult;
file.seekg(0);
bool bBom = false;
// 读取前3个字节
std::vector<char> buffer(3);
file.read(buffer.data(), 3);
// 检查是否是 UTF-8 BOM
if (buffer.size() >= 3 &&
static_cast<unsigned char>(buffer[0]) == 0xEF &&
static_cast<unsigned char>(buffer[1]) == 0xBB &&
static_cast<unsigned char>(buffer[2]) == 0xBF) {
bBom = true;
}
_Mem<char> m(length + 1);
if (bBom) {
file.read(m.data(), length - 3);
m.setElementCount(length - 3);
}
else {
file.seekg(0);
file.read(m.data(), length);
m.setElementCount(length);
}
//托管m的内存
sResult.setManagedMemoryFrom(m);
file.close();
return sResult;
}