如何将文件系统路径转换为字符串 [英] how to convert filesystem path to string

查看:758
本文介绍了如何将文件系统路径转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历文件夹中的所有文件,只希望它们的名称在字符串中。我想从 std :: filesystem :: path 获取一个字符串。我该怎么做?

I am iterating through all the files in a folder and just want their names in a string. I want to get a string from a std::filesystem::path. How do I do that?

我的代码:

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::experimental::filesystem;

int main()
{
    std::string path = "C:/Users/user1/Desktop";
    for (auto & p : fs::directory_iterator(path))
        std::string fileName = p.path;
}

但是我收到以下错误:

non-standard syntax; use '&' to create a pointer to a member.


推荐答案

要转换 std :: filesystem :: path 到本地-编码的字符串(其类型为 std :: filesystem :: path :: value_type ),请使用 string() 方法。请注意其他 * string()方法,这些方法使您能够获取特定编码的字符串(例如 u8string()

To convert a std::filesystem::path to a natively-encoded string (whose type is std::filesystem::path::value_type), use the string() method. Note the other *string() methods, which enable you to obtain strings of a specific encoding (e.g. u8string() for an UTF-8 string).

C ++ 17示例:

C++17 example:

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

int main()
{
    fs::path path{fs::u8path(u8"愛.txt")};
    std::string path_string{path.u8string()};
}

C ++ 20示例(更好的语言和库UTF-8支持):

C++20 example (better language and library UTF-8 support):

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

int main()
{
    fs::path path{u8"愛.txt"};
    std::u8string path_string{path.u8string()};
}

这篇关于如何将文件系统路径转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆