LPCWSTR to string conversion issue in code c++ VS 2010

306 views Asked by At

I am trying to find files with specific name and deleting them in c++ as this code works fine if i give direct desktop path to it L"path//" but as path of desktop is different due to different user and system so i what i am doing at the top is to get desktop path in string variable and assigning it rather than direct path.

string desk=getenv("DESKTOP");


        WIN32_FIND_DATAW fd;
        HANDLE hFind = FindFirstFileW(desk, &fd);
        if (hFind != INVALID_HANDLE_VALUE)
        {
            do
            {
                DeleteFileW((wstring(desk) + fd.cFileName).c_str());
            } while (FindNextFileW(hFind, &fd));
            FindClose(hFind);
        }

I am getting the following error

Error 4 error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'std::string' to 'LPCWSTR'

I have already tried using wstring and wchar but it gives error again. Can anyone please help me to sortout this issue. looking for correction in code

2

There are 2 answers

0
Zebrafish On

Windows will usually have two versions of a function, an A suffix will generally be it accepts chars, a W suffix accepts a wchar_t, and without the suffix usually ends up as a macro for whatever character set is selected. Generally the string types they will accept is LPCWSTR (long pointer to wide constant string) or LPCSTR (long pointer to constant string).

First argument of FindFirstFileW() takes a LPCWSTR.

LPCWSTR is a typedef for const wchar_t*. You are passing an std::string, so it's the wrong type.

Just be consistent with the string type, either do:

wstring desk = _wgetenv(L"DESKTOP");

string findDigitsInBinary(int A) {

    WIN32_FIND_DATAW fd;

    HANDLE hFind = FindFirstFileW(desk.c_str(), &fd); // First argument takes LPCWSTR

or:

string desk = getenv("DESKTOP");

string findDigitsInBinary(int A) {

    WIN32_FIND_DATAA fd;

    HANDLE hFind = FindFirstFileA(desk.c_str(), &fd); // First arg takes LPCSTR

Notice that in neither case you are passing the string class, but the character buffer held by the string.

The suffixes W and A I think stand for wide and ANSI.

0
MSalters On

Since you're calling Win32 functions directly, consistency suggests using GetEnvironmentVariableW instead of getenv. The reliance on a DESKTOP variable is already very Windows-specific; this isn't portable code by any means.