c++ - 打开具有 unicode 路径的文件

标签 c++ boost unicode

我在 Windows 7 下使用 mingw 工作。我在使用 unicode 文件名时遇到了一些奇怪的行为。我的程序需要可移植,我正在使用 boost::filesystem (v 1.53) 来处理文件路径。

一切都很顺利,直到我需要打开具有 unicode 文件名的文件。 这与文件的内容无关,而是文件的名称。

我尝试了以下操作:为了测试,我创建了一个名为 C:\UnicodeTest\вячеслав 的文件夹,并尝试在其中创建一个文件,方法是附加文件名 test.txt 到 boost wpath。 由于某种原因,文件创建失败。我正在使用 boost 的 fstream,当我尝试打开文件时,设置了流的 failbit。 现在有趣的是,当我将文件夹名称附加到路径时,对 create_directories() 的调用成功并创建了正确的目录 C:\UnicodeTest\вячеслав\folder.

我真的不明白为什么它不能处理文件。这是我使用的代码:

boost::filesystem::wpath path;

// find the folder to test
boost::filesystem::wpath dirPath = "C:\\UnicodeTest";
vector<boost::filesystem::wpath> files;
copy(boost::filesystem::directory_iterator(dirPath), boost::filesystem::directory_iterator(), back_inserter(files));

for(boost::filesystem::wpath &file : files)
{
    if(boost::filesystem::is_directory(file))
    {
        path = file;
        break;
    }
}

// create a path for the folder
boost::filesystem::wpath folderPath = path / "folder";
// this works just fine
boost::filesystem::create_directories(folderPath);

// create a path for the file
boost::filesystem::wpath filePath = path / "test.txt";

boost::filesystem::ofstream stream;

// this fails
stream.open(filePath);

if(!stream)
{
    cout << "failed to open file " << path << endl;
}
else
{
    cout << "success" << endl;
}

最佳答案

如果我没有理解错的话,C:\UnicodeTest\вячеслав 中无法直接创建文件的问题是在不创建文件夹目录时出现的,如下图所示。

// create a path for the folder
//boost::filesystem::wpath folderPath = path / "folder";
// this works just fine
//boost::filesystem::create_directories(folderPath);

// create a path for the file
boost::filesystem::wpath filePath = path / "test.txt";

我可以通过将文件名设为 wchar_t 字符串来让它工作:

// create a path for the file
boost::filesystem::wpath filePath = path / L"test.txt";

关于c++ - 打开具有 unicode 路径的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875025/

相关文章:

c++ - 为什么我不能从 C++ 中的 int 继承?

c++ - Boost.MultiArray 的一行初始化器

c++ - Boost::iostreams::filtering_istreams 等待 E.O.F

c++ - 用 std::tr1::bind 替换 boost::bind 时出现问题

java - 如何在 Java 中匹配 unicode 字符

c++ - 继续学习高级 C++ 的最佳方式是什么?

c++ - 将 future 与 boost::asio 结合使用

c++ - 我如何优化此代码以这种格式打印?

windows - 是否有适用于 Windows 的 Unicode 字体,它与 Arial Unicode MS 一样完整,但免费,甚至可用于商业用途?

python - unicode 和 python 请求发生了一些有趣的事情