如何将文件系统路径转换为字符串
how to convert filesystem path to string
我正在遍历文件夹中的所有文件,只希望它们的名称在一个字符串中。我想从std::filesystem::path
中获取字符串.我该怎么做?
我的代码:
#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()
方法,它们使您能够获得特定编码的字符串(例如 对于 UTF-8 字符串u8string()
(。
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 示例(更好的语言和库 UTF-8 支持(:
#include <filesystem>
#include <string>
namespace fs = std::filesystem;
int main()
{
fs::path path{u8"愛.txt"};
std::u8string path_string{path.u8string()};
}
在 C++ 17 及更高版本中,您可以使用 .generic_string(( 将路径转换为字符串:https://en.cppreference.com/w/cpp/filesystem/path/generic_string。
下面是获取当前工作目录并将其转换为字符串的示例。
#include <string>
#include <filesystem>
using std::filesystem::current_path;
int main()
{
filesystem::path directoryPath = current_path();
string stringpath = directoryPath.generic_string();
}
使用 UTF-8 操作的公认答案中给出的示例很好,是一个很好的指南。答案中给出的介绍性解释中只有一个错误,Windows/MSVC 开发人员应该注意:
string()
方法不返回本机编码的字符串(在 Windows 上会std::wstring()
(,而是始终返回std::string
。它还尝试将路径转换为本地编码,如果路径包含当前代码页中不可表示的 unicode 字符,然后该方法引发异常,则并不总是可行的!
如果你真的想要答案中描述的行为(方法返回本机字符串,即在 Linux 上std::string
,在 Windows 上std::wstring
(,你必须使用native()
方法或基于std::filesystem::path::operator string_type()
的隐式转换,但正如@tambre示例中正确指出的那样,您应该考虑始终使用 UTF-8 版本。
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数