在 C++17 中引入了 std::filesystem
标准库,提供了 std::filesystem::path
类型来处理文件路径。你可以使用该库来进行 std::filesystem::path
和 std::string
之间的转换。以下是一些示例代码:
- 将
std::string
转换为std::filesystem::path
:
#include <filesystem>
#include <string>namespace fs = std::filesystem;int main() {std::string strPath = "/path/to/file.txt";fs::path filePath(strPath);// 或者直接使用构造函数// fs::path filePath = strPath;return 0;
}
2. 将 std::filesystem::path
转换为 std::string
:
#include <filesystem>
#include <string>namespace fs = std::filesystem;int main() {fs::path filePath = "/path/to/file.txt";std::string strPath = filePath.string();return 0;
}