#include #include #include

bool isUTF16LE(std::ifstream& file) { uint16_t bom; file.read(reinterpret_cast<char*>(&bom), sizeof(bom)); return bom == 0xFEFF; }

bool isUTF16BE(std::ifstream& file) { uint16_t bom; file.read(reinterpret_cast<char*>(&bom), sizeof(bom)); bom = (bom >> 8) | (bom << 8); // 字节序转换 return bom == 0xFEFF; }

bool isUTF32LE(std::ifstream& file) { uint32_t bom; file.read(reinterpret_cast<char*>(&bom), sizeof(bom)); return bom == 0xFEFF; }

bool isUTF32BE(std::ifstream& file) { uint32_t bom; file.read(reinterpret_cast<char*>(&bom), sizeof(bom)); bom = ((bom >> 24) & 0xFF) | ((bom >> 8) & 0xFF00) | ((bom << 8) & 0xFF0000) | ((bom << 24) & 0xFF000000); // 字节序转换 return bom == 0xFEFF; }

bool isUTF8(std::ifstream& file) { char bom[3]; file.read(bom, sizeof(bom)); return bom[0] == static_cast(0xEF) && bom[1] == static_cast(0xBB) && bom[2] == static_cast(0xBF); }

int main() { std::string filename; std::cout << "请输入文件名: "; std::cin >> filename;

std::ifstream file(filename, std::ios::binary);
if (!file) {
    std::cout << "无法打开文件" << std::endl;
    return 1;
}

std::cout << "检测结果:" << std::endl;
if (isUTF16LE(file)) {
    std::cout << "UTF16LE无签名" << std::endl;
}
if (isUTF16BE(file)) {
    std::cout << "UTF16BE无签名" << std::endl;
}
if (isUTF32LE(file)) {
    std::cout << "UTF32LE无签名" << std::endl;
}
if (isUTF32BE(file)) {
    std::cout << "UTF32BE无签名" << std::endl;
}
if (isUTF8(file)) {
    std::cout << "UTF8无签名" << std::endl;
}

return 0;

}

请注意,上述代码假设输入的文件是有效的编码文件,且文件名需要包含文件的完整路径。


原文地址: https://www.cveoy.top/t/topic/p8g7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录