1

I'm trying to convert const std::filesystem::directory_entry (dirent) to tchar but I don't understand how it an be done. I tried a lot of ways. Can you help me?

Edited:

 #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';
    }
Pranciskus
  • 487
  • 1
  • 6
  • 17
  • 1
    There's no filesystem function that converts to a TCHAR. I'd recommend avoiding TCHAR (which only exists so you can cross compile for Windows 95 and Windows XP, hardly an important concern any more). Better these days to use wide characters, WCHAR in Windows. Then you can just do `wcscpy(path, dirent.c_str());` There's nothing you can do with TCHAR that you can't do with the equivalent WCHAR routine, so TCHAR really isn't needed any more. – john Aug 09 '19 at 10:05
  • I just added typedef wchar_t WCHAR; and replaced TCHAR to WCHAR path[_MAX_PATH]; wcscpy(path, dirent.c_str()); but it says: error C2039: 'c_str': is not a member of 'std::filesystem::directory_entry' – Pranciskus Aug 09 '19 at 10:15

1 Answers1

1

You can convert std::filesystem::path to any form using these functions:

std::string string() const;
std::wstring wstring() const;
std::u16string u16string() const;
std::u32string u32string() const;

TCHAR is somewhat of a relic as mentioned in the comments, and you're much better off using any of the above alternatives.

If you're going to pass it to Win32 API functions, I would either suggest using wstring explicitly and not bother with the shape-shifting TCHAR at all.


What your code should look like is this:

if (fs::is_regular_file(dirent) &&
    dirent.path().filename() == "black.txt")
{    
    std::wstring path_as_string = path.wstring();
}

No TCHAR, no C-style arrays no C-style memory copying.

rubenvb
  • 74,642
  • 33
  • 187
  • 332