alwaystudent
alwaystudent

Reputation: 181

cannot convert FindFileData.cFileName to string

I am making great headways but I have 2 problems that have been slowing me down for days. The biggest is that I want to save FindFileData.cFileName as string but I cannot ! Any help ?

Upvotes: 5

Views: 9011

Answers (2)

alwaystudent
alwaystudent

Reputation: 181

I copied this from here: How to convert wstring into string? It converts wstring directly to string ( including FindFileData.cFileName). Any better suggestion or any useful comment ?

#include <clocale>
#include <locale>
#include <string>
#include <vector>

inline std::string narrow(std::wstring const& text)
{
    std::locale const loc("");
    wchar_t const* from = text.c_str();
    std::size_t const len = text.size();
    std::vector<char> buffer(len + 1);
    std::use_facet<std::ctype<wchar_t> >(loc).narrow(from, from + len, '_', &buffer[0]);
    return std::string(&buffer[0], &buffer[len]);
}

Upvotes: 2

hmjd
hmjd

Reputation: 121961

From WIN32_FIND_DATA reference page cFileName is of type TCHAR[]. If UNICODE is enabled (TCHAR is wchar_t) use std::wstring:

#include <string>
std::wstring ws(FindFileData.cFileName);

otherwise use std::string (as TCHAR is char):

std::string ws(FindFileData.cFileName);

Or, to cater for both:

std::basic_string<TCHAR> s(FindFileData.cFileName);
// std::string is a typedef for std::basic_string<char>
// std::wstring is a typedef for std::basic_string<wchar_t>

Upvotes: 1

Related Questions