C++有没有类似于Python的os.path.join
函数的等价物呢?基本上,我正在寻找一些可以将文件路径的两个(或更多)部分组合起来,以便您不必担心确保这两个部分完美匹配的东西。如果是在Qt中,那也很酷。
基本上,我花了一个小时调试一些代码,而其中至少一部分是因为root + filename
必须是root/ + filename
,我想在以后避免这种情况。
C++有没有类似于Python的os.path.join
函数的等价物呢?基本上,我正在寻找一些可以将文件路径的两个(或更多)部分组合起来,以便您不必担心确保这两个部分完美匹配的东西。如果是在Qt中,那也很酷。
基本上,我花了一个小时调试一些代码,而其中至少一部分是因为root + filename
必须是root/ + filename
,我想在以后避免这种情况。
仅作为 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;
}
$ g++ ./test.cpp -o test -lboost_filesystem -lboost_system
$ ./test
/tmp/foo.txt
#include <filesystem>
,namespace fs = std::filesystem;
。使用C++14,使用#include <experimental/filesystem>
,namespace fs = std::experimental::filesystem;
。 - Roi Dantonboost
),此功能作为std::filesystem
的一部分可用。以下代码使用Homebrew GCC 9.2.0_1
编译,并使用标志--std=c++17
:#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;
}
A + B
,fs::path
重载运算符 /
/ +
来进行追加/连接。请参考 https://en.cppreference.com/w/cpp/filesystem/path/concat。 - Kevin Chan这个可以查看QDir:
QString path = QDir(dirPath).filePath(fileName);
QFileInfo
构造函数:QFileInfo fi( QDir("/tmp"), "file" );
QString path = fi.absoluteFilePath();
使用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...));
}
使用方法:
QString path = join("/tmp", "dir", "file"); // /tmp/dir/file
QDir::toNativeSeparators( path );
它将使用本地等效项(即 Windows 上的 \
)替换 /
。另一方面,可以通过 QDir::fromNativeSeparators()
实现。
这里提供了一个非常简单的C++11友好的替代方案,适用于那些既没有Boost、Qt也没有C++17的人(摘自这里)。
std::string pathJoin(const std::string& p1, const std::string& p2)
{
char sep = '/';
std::string tmp = p1;
#ifdef _WIN32
sep = '\\';
#endif
// Add separator if it is not included in the first path:
if (p1[p1.length() - 1] != sep) {
tmp += sep;
return tmp + p2;
} else {
return p1 + p2;
}
}
p1[p1.length() - 1] != sep
而不是 p1[p1.length()] != sep
。我们还可以考虑到 Windows 接受 '\\'
和 '/'
两种路径分隔符。 - Rotem