打开具有unicode路径的文件

Open a file with unicode path

本文关键字:路径 文件 unicode      更新时间:2023-10-16

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

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

为了测试,我创建了一个名为C:UnicodeTestвячеслав的文件夹,并尝试在其中创建一个文件,通过将文件名test.txt附加到boost wpath。由于某种原因,文件的创建失败了。我正在使用boost的fstream s,当我试图打开文件时,设置了流的失败位。现在有趣的是,当我将文件夹名附加到路径时,对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;
}

如果我正确理解了这个问题,那么当您不创建folder目录时,就会出现无法直接在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";