C++でエンコード自動判断関数

#include <fstream>
#include <iostream>
#include <vector>

// エンコーディングを判断するための関数
std::string GetFileEncoding(const std::string& filePath) {
    std::ifstream file(filePath, std::ios::binary);
    if (!file) {
        return "Unknown";
    }

    std::vector<unsigned char> buffer(4);
    file.read(reinterpret_cast<char*>(&buffer[0]), 4);

    if (file.gcount() >= 2) {
        if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) {
            return "UTF-8";
        } else if (buffer[0] == 0xFF && buffer[1] == 0xFE) {
            return "UTF-16LE";
        } else if (buffer[0] == 0xFE && buffer[1] == 0xFF) {
            return "UTF-16BE";
        }
    }

    // デフォルトエンコーディング(例: Shift-JIS)を判断するための追加のロジックをここに追加できます

    return "Shift-JIS";
}

int main() {
    std::string csvFilePath = "your_csv_file.csv";

    std::string encoding = GetFileEncoding(csvFilePath);
    std::cout << "File Encoding: " << encoding << std::endl;

    return 0;
}