如何将CSV文件保存为UTF-8

How to save a CSV file as UTF-8

本文关键字:保存 UTF-8 文件 CSV      更新时间:2023-10-16

i编写代码来创建。CSV文件带有泰语字符。但是,当我使用该文件中的Microsoft Excel thai字符打开文件时,当我在记事本中打开它时,然后按保存。并再次在Excel中打开。我认为这是因为该程序未编码UTF-8。我必须做编程,将其保存为UTF-8。

std:: ofstream MyCSVFile;
MyCSVFile.open("myfile.csv", std::ios::out | std::ios::app);
MyCSVFile << "Name,Address" << endl;
MyCSVFile <<name<<","<<address << endl;
MyCSVFile.close();
}

您需要将BOM写入文件的开头。尝试以下操作:

const char *bom = "xefxbbxbf";
MyCSVFile << bom;
MyCSVFile << "Name...

这是一个很好的阅读:bom in wikipedia。

您需要执行以下操作(假设文件路径存储在FilePath中):这是您应该使用的代码:

const std::wstring fileStr(FilePath);
wofstream mFile(FilePath);

mFile.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>));
if (mFile.is_open())
{
    const wchar_t *bom = L"xefxbbxbf";
    mFile << bom;
...

现在您可以写文本,当然可以关闭文件。