C++ 如何将文件系统路径转换为字符串

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

how to convert filesystem path to string

c++c++17

提问by anonymous noob

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?

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

My code:

我的代码:

#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;
}

However I get the following error:

但是我收到以下错误:

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

回答by tambre

To convert a std::filesystem::pathto 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).

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

C++17 example:

C++17 示例:

#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 example (better language and library UTF-8 support):

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

#include <filesystem>
#include <string>

namespace fs = std::filesystem;

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