LPCTSTR typecast for use with GetFileAttributes

十年热恋 提交于 2019-12-13 21:08:06

问题


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?


回答1:


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:

  • Converting string to tchar in VC++



回答2:


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());


来源:https://stackoverflow.com/questions/23924473/lpctstr-typecast-for-use-with-getfileattributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!