![](/img/trans.png)
[英]How to convert const std::filesystem::directory_entry& to string in c++
[英]How to convert const std::filesystem::directory_entry to tchar?
我正在嘗試將const std :: filesystem :: directory_entry(dirent)轉換為tchar,但我不知道該怎么做。 我嘗試了很多方法。 你能幫助我嗎?
編輯:
#include "pch.h"
#include <memory>
#include <filesystem>
#include <algorithm>
#include <iostream>
#include <tchar.h>
#include <string.h>
typedef wchar_t WCHAR;
namespace fs = std::filesystem;
int main() try
{
std::for_each(fs::recursive_directory_iterator("./foo/"), {},
[](fs::directory_entry const& dirent)
{
if (fs::is_regular_file(dirent) &&
dirent.path().filename() == "black.txt")
{
std::wstring = path.wstring();
}
});
}
catch (fs::filesystem_error const& e)
{
std::cerr << "error: " << e.what() << '\n';
}
您可以使用以下功能將std::filesystem::path
轉換為任何形式:
std::string string() const;
std::wstring wstring() const;
std::u16string u16string() const;
std::u32string u32string() const;
如評論中所述, TCHAR
有點像遺物,而使用上述任何一種替代方法,您的狀況都會更好。
如果要將其傳遞給Win32 API函數,我要么建議顯式使用wstring
,要么完全wstring
會變形的TCHAR
。
您的代碼應如下所示:
if (fs::is_regular_file(dirent) &&
dirent.path().filename() == "black.txt")
{
std::wstring path_as_string = path.wstring();
}
沒有TCHAR
,沒有C樣式的數組,沒有C樣式的內存復制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.