- 下载uchardet源码
GitHub - BYVoid/uchardet: An encoding detector library ported from Mozilla · GitHub
- 编译
2.1 mkdir build
2.2 cmake ..
2.3 make
2.4 sudo make install
2.5 使用
cpp
#include <iostream>
#include <fstream>
#include <uchardet/uchardet.h>
int main() {
std::ifstream file("example.txt", std::ios::binary);
if (!file) {
std::cerr << "无法打开文件" << std::endl;
return 1;
}
uchardet_t ud = uchardet_new();
char buffer[4096];
while (file.read(buffer, sizeof(buffer))) {
uchardet_handle_data(ud, buffer, file.gcount());
}
uchardet_handle_data(ud, buffer, file.gcount());
uchardet_data_end(ud);
const char* encoding = uchardet_get_charset(ud);
std::cout << "检测到的编码: " << encoding << std::endl;
uchardet_delete(ud);
return 0;
}
g++ -o detect_encoding detect_encoding.cpp -luchardet
./detect_encoding