4

我正在尝试使用 boost 创建相对路径。

我最初的计划是:

string base_directory;  // input
boost::filesystem::path base_path;
string other_directory;  // input
boost::filesystem::path other_path;
// assume base_path is absolute - did that already (using complete() 
// if path is relative, to root it in the current directory)  -> 
base_directory = base_path.string();

if (other_path.empty())
  other_directory = base_directory;
else
{
  other_path = boost::filesystem::path(other_directory);        
  if(!other_path.is_complete())
  {
    other_path = base_path / other_path;
    other_directory = other_path.string();          
  }
  if(!boost::filesystem::exists(boost::filesystem::path(other_path)))
  {
    boost::filesystem::create_directory(other_path);
  }
}

如果 other_directory 是绝对的或只是一个名称(或相对于 base_directory 的内部),这可以正常工作。

但是如果我尝试输入“..”或“../other”,我最终会得到奇怪的结构,例如“c:\test..”或“c:\test..\other”

如何正确创建相对路径,最好使用 boost ?我试图查看文档......没有积极的成功。

我正在使用 Windows(我对 boost 的偏好是它应该是多平台的,我已经依赖它了)

编辑:我有提升 1.47

谢谢你的任何建议。

4

1 回答 1

1

Boost 文件系统不知道是"C:\test"指文件还是目录,因此它不会假设尾随"\"是正确的。

如果添加"\",则可以使用该功能boost::filesystem::canonical()来简化删除...元素的路径。

other_path = boost::filesystem::path( other_directory + "\" );        
if(!other_path.is_complete())
{
  other_path = boost::filesystem::canonical( base_path / other_path );
于 2013-04-24T22:03:46.003 回答