C++ boost::filesystem 相对路径和当前目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3935874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:05:47  来源:igfitidea点击:

boost::filesystem relative path and current directory?

c++boostfilesystems

提问by Jake

How can I use boost::filesystem::pathto specify a relative path on Windows? This attempt fails:

如何boost::filesystem::path在 Windows 上指定相对路径?此尝试失败:

boost:filesystem::path full_path("../asset/toolbox"); // invalid path or directory.

Maybe to help me debug, how to get the current working directory with boost::filesystem?

也许是为了帮助我调试,如何使用 boost::filesystem 获取当前工作目录?

回答by hmuelner

getcwd = boost::filesystem::path full_path(boost::filesystem::current_path());

Example:

例子:

boost::filesystem::path full_path(boost::filesystem::current_path());
std::cout << "Current path is : " << full_path << std::endl;

To access current_pathone needs to add #include <boost/filesystem.hpp>.

要访问current_path一个需要添加#include <boost/filesystem.hpp>.

回答by ulidtko

Try the system_completefunction.

试试这个system_complete功能。

namespace fs = boost::filesystem;

fs::path full_path = fs::system_complete("../asset/toolbox");

This mimics exactly how the OS itself would resolve relative paths.

这准确地模仿了操作系统本身如何解析相对路径。

回答by serup

If you want to change to previous directory then try something like this:

如果要更改到上一个目录,请尝试以下操作:

boost::filesystem::path full_path( boost::filesystem::current_path() );
std::cout << "Current path is : " << full_path << std::endl;

//system("cd ../"); // change to previous dir -- this is NOT working
chdir("../"); // change to previous dir -- this IS working

boost::filesystem::path new_full_path( boost::filesystem::current_path() );
std::cout << "Current path is : " << new_full_path << std::endl;

回答by Midnighter

When you type "../your/path" aren't you specifying a unix-like path? I think what you should do to get system specific paths is:

当您输入“../your/path”时,您不是指定了一个类 Unix 路径吗?我认为你应该怎么做才能获得系统特定的路径:

boost:filesystem::path full_path(".." / "asset" / "toolbox");

In this case the '/' is an operator concatenating paths in a system specific way and is not part of the path that you specify.

在这种情况下,“/”是以系统特定方式连接路径的运算符,而不是您指定的路径的一部分。