C++ 如何从单独的字符串(安全地)构建完整路径字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6297738/
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 19:52:56  来源:igfitidea点击:

How to build a full path string (safely) from separate strings?

c++qtfilepath

提问by sas4740

Does C++ have any equivalent to python's function os.path.join? Basically, I'm looking for something that combines two (or more) parts of a file path so that you don't have to worry about making sure the two parts fit together perfectly. If it's in Qt, that would be cool too.

C++ 有什么等同于 python 的函数os.path.join吗?基本上,我正在寻找将文件路径的两个(或更多)部分组合在一起的东西,这样您就不必担心确保这两个部分完美地结合在一起。如果它在 Qt 中,那也会很酷。

Basically I spent an hour debugging some code and at least part of it was because root + filenamehad to be root/ + filename, and I'm looking to avoid that in the future.

基本上我花了一个小时调试一些代码,至少有一部分是因为root + filename必须是root/ + filename,我希望将来避免这种情况。

采纳答案by Stephen Chu

Check out QDirfor that:

检查QDir

QString path = QDir(dirPath).filePath(fileName);

回答by

Only as part of Boost.Filesystemlibrary. Here is an example:

仅作为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;
}

Here is an example of compiling and running (platform specific):

这是编译和运行的示例(特定于平台):

$ g++ ./test.cpp -o test -lboost_filesystem -lboost_system
$ ./test 
/tmp/foo.txt

回答by Shawn Blakesley

Similar to @user405725's answer (but not using boost), and mentioned by @ildjarnin a comment, this functionality is available as part of std::filesystem. The following code compiles using Homebrew GCC 9.2.0_1 and using the flag --std=c++17:

类似于@user405725的答案(但不使用 boost),并且@ildjarn在评论中提到,此功能可作为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;
}

回答by frankc

At least in Unix / Linux, it's always safe to join parts of a path by /, even if some parts of the path already end in /, i.e. root/pathis equivalent to root//path.

至少在 Unix / Linux 中,/即使路径的某些部分已经以 结尾/,即root/path相当于root//path.

In this case, all you really need is to join things on /. That said, I agree with other answers that boost::filesystemis a good choice if it is available to you because it supports multiple platforms.

在这种情况下,您真正​​需要的只是加入/. 也就是说,我同意其他答案,boost::filesystem如果您可以使用它是一个不错的选择,因为它支持多个平台。

回答by LoSciamano

If you want to do this with Qt, you can use QFileInfoconstructor:

如果你想用 Qt 做到这一点,你可以使用QFileInfo构造函数:

QFileInfo fi( QDir("/tmp"), "file" );
QString path = fi.absoluteFilePath();

回答by kainjow

With C++11 and Qt you can do this:

使用 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...));
}

Usage:

用法:

QString path = join("/tmp", "dir", "file"); // /tmp/dir/file

回答by Frank Osterfeld

In Qt, just use /in code when using Qt API (QFile, QFileInfo). It will do the right thing on all platforms. If you have to pass a path to a non-Qt function, or want to format it for displaying it to the user, use QDir:toNativeSeparators()e.g.:

在 Qt 中,/当使用 Qt API ( QFile, QFileInfo)时,只需在代码中使用。它会在所有平台上做正确的事情。如果您必须将路径传递给非 Qt 函数,或者想要对其进行格式化以将其显示给用户,请使用QDir:toNativeSeparators()例如:

QDir::toNativeSeparators( path );

It will replace /by the native equivalent (i.e. \on Windows). The other direction is done via QDir::fromNativeSeparators().

它将替换/为本地等效项(即\在 Windows 上)。另一个方向是通过QDir::fromNativeSeparators().