文件路径作为字符串传递.如何将此字符串转换为std :: filesystem :: path?例:
#include <filesystem>
std::string inputPath = "a/custom/path.ext";
const std::filesystem::path path = inputPath; // Is this assignment safe?
Run Code Online (Sandbox Code Playgroud)
Bar*_*rry 12
是的,这种结构是安全的:
const std::filesystem::path path = inputPath; // Is this assignment safe?
Run Code Online (Sandbox Code Playgroud)
那不是赋值,即复制初始化.您正在调用此构造函数:
template< class Source >
path( const Source& source );
Run Code Online (Sandbox Code Playgroud)
需要:
构造路径从source(4)提供的字符序列,它是指针或输入迭代器到以null结尾的字符/宽字符序列,a
std::basic_string或anstd::basic_string_view,
所以你没事.另外,如果你不能从a 构造一个,那将是非常奇怪filesystem::path的std::string.
小智 9
我知道这是一个 5 年前的问题,但由于它仍然是搜索“string to filesystem::path”的最高结果,恕我直言,它需要对 Windows 上的用法进行一些额外的评论(尽管最初的问题可能是隐含的)重点关注 Linux,从所选的路径分隔符来看)。
对于 Windows 系统,从字符串隐式构造 filesystem::path在编码方面并不安全(尽管根据标准它是合法的)。如果你有一个包含非 ASCII 字符的 std::string 路径,你必须绝对清楚它是用本地代码页还是 UTF-8 编码的(Linux 下没有这样的区别)。问题中显示的隐式构造将假定本地代码页中的编码,而许多第三方库将假定 UTF-8 作为标准(例如 QString::toStdString() 中的 QT 返回 UTF-8;gRPC/protobuf 中的字符串应该是 UTF-8 等)。因此,你必须非常小心,不要混合使用这些:
const std::string path_as_string = "\xe4\xb8\xad"; //chinese character Zhong in UTF-8
const std::filesystem::path wrong_path = path_as_string; //looks innocent, but incorrect encoding is used!
std::ofstream stream;
stream.open(std::filesystem::current_path() / wrong_path); //create a file with the broken name
stream.close();
Run Code Online (Sandbox Code Playgroud)
在这种情况下构建路径的正确方法是
const std::filesystem::path correct_path = std::filesystem::u8path(path_as_string);
Run Code Online (Sandbox Code Playgroud)
另请注意,这是一个完全有效的路径,您可以使用常规应用程序或 Windows 资源管理器轻松创建包含此类字符的文件。由于转换错误的可能性很大,恕我直言,在当前情况下最好不要有任何隐式构造函数,但在 STL 实现中提供禁用该行为的选项的请求已被拒绝参考标准。另一方面,Windows 似乎将来会慢慢转向 UTF-8 作为默认代码页(参见例如此评论)。在此之前,应考虑上述注意事项。
| 归档时间: |
|
| 查看次数: |
5534 次 |
| 最近记录: |