0

I´m trying to build a method to see if a file exists. the method in it´s current isn´t complete form. i´m trying to figur out whyy it doesn´t behave as code.

    BOOL FileExists(LPCTSTR szPath)
        {
            //MessageBox(NULL,szPath,L"File Error",MB_OK);
          DWORD dwAttrib = GetFileAttributes(szPath);

            switch(dwAttrib)
            {

                case FILE_ATTRIBUTE_DIRECTORY:
                    MessageBox(NULL,L"FILE_ATTRIBUTE_DIRECTORY",L"File Error",MB_OK);
                    break;
                case FILE_ATTRIBUTE_ARCHIVE:
                    MessageBox(NULL,L"FILE_ATTRIBUTE_ARCHIVE",L"File Error",MB_OK);
                    break;
                case FILE_READ_ONLY_VOLUME:
                    MessageBox(NULL,L"FILE_READ_ONLY_VOLUME",L"File Error",MB_OK);
                    break;
                case FILE_INVALID_FILE_ID:
                    MessageBox(NULL,L"FILE_INVALID_FILE_ID",L"File Error",MB_OK);
                    break;
                default:
                    MessageBox(NULL,(LPCWSTR)dwAttrib,L"File Error",MB_OK);
                    break;
            }
return true;
        }

this is how i call the method:

FileExists((LPCWSTR)path.c_str());

this is where my file resides:

std::string path = "C:\\smiley.bmp"

i always end up here, no mather in what order the switched is coded:

FILE_INVALID_FILE_ID

i'm wondering if i'm typecastings correct to "LPCTSTR".

Because i tried using a MessageBox to display the contents of "szPath" and it showed up as human unreadeble format.

the path i provide is correct, properly escaped. how can i check if "szPath" contains the proper information?

NaturalDemon
  • 934
  • 1
  • 9
  • 21

2 Answers2

4

std::string is based on char, so when you call .c_str(), you can a char *.

But LPCWSTR is a pointer to a wide character string.

I believe, if you're compiling with UNICODE enabled (so LPCTSTR == LPCWSTR), you'll need to use std::wstring.

Relevant:

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • thank you for your answer. but i´m a bit lost now! http://en.cppreference.com/w/cpp/string/basic_string/to_wstring what do i need to change? – NaturalDemon May 29 '14 at 02:27
1

Casting does not convert a string into a wide string. It just tells the compiler to shut up, and the error will move. You need the L prefix on literal strings to make them wide strings. And you need to use wstring instead of string.

std::wstring path = L"C:\\smiley.bmp";
FileExists(path.c_str());
ScottMcP-MVP
  • 10,337
  • 2
  • 15
  • 15
  • Ok, i did it wrong and forgot to add the 'L' in the path variable. the software compiles fine, but still i hit the same point 'FILE_INVALID_FILE_ID'. i added #include , it should work, because the file is on that spot – NaturalDemon May 29 '14 at 15:20