C++有没有与python函数相同的东西os.path.join?基本上,我正在寻找一种结合文件路径的两个(或更多)部分的东西,这样您就不必担心确保两个部分完美地结合在一起.如果它在Qt中,那也很酷.
基本上我花了一个小时调试一些代码,至少部分代码是因为root + filename必须root/ + filename,并且我希望将来避免这种情况.
小智 94
仅作为Boost.Filesystem库的一部分.这是一个例子:
#include <iostream>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
int main ()
{
fs::path dir ("/tmp");
fs::path file ("foo.txt");
fs::path full_path = dir / file;
std::cout << full_path << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下是编译和运行的示例(特定于平台):
$ g++ ./test.cpp -o test -lboost_filesystem -lboost_system
$ ./test
/tmp/foo.txt
Run Code Online (Sandbox Code Playgroud)
Ste*_*Chu 39
查看QDir:
QString path = QDir(dirPath).filePath(fileName);
Run Code Online (Sandbox Code Playgroud)
Sha*_*ley 19
类似于@ user405725的答案(但不使用boost),并且在评论中由@ildjarn提及,此功能作为std :: experimental :: filesystem的一部分提供.以下代码使用Microsoft Visual Studio 2015 Community Edition进行编译:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path dir ("/tmp");
fs::path file ("foo.txt");
fs::path full_path = dir / file;
std::cout << full_path << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
至少在Unix/Linux中,/即使路径的某些部分已经结束/,即root/path等同于,也可以安全地连接路径的一部分root//path.
在这种情况下,您真正需要的就是加入/.也就是说,我同意其他答案,boost::filesystem如果你可以使用它是一个很好的选择,因为它支持多个平台.
如果你想用Qt做这个,你可以使用QFileInfo构造函数:
QFileInfo fi( QDir("/tmp"), "file" );
QString path = fi.absoluteFilePath();
Run Code Online (Sandbox Code Playgroud)
使用 C++11 和 Qt,你可以这样做:
QString join(const QString& v) {
return v;
}
template<typename... Args>
QString join(const QString& first, Args... args) {
return QDir(first).filePath(join(args...));
}
Run Code Online (Sandbox Code Playgroud)
用法:
QString path = join("/tmp", "dir", "file"); // /tmp/dir/file
Run Code Online (Sandbox Code Playgroud)