我在 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/