简体   繁体   中英

Very Strange Behavior of LPCTSTR

I've been working on a system to reversivly search directories with FindFirstFile and FindNextFile but I've encountered an issue that I don't understand.

Below is a code snippet.

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine
                  ,int nCmdShow)
{    
    searchDrive((LPCTSTR)"C:\\",(LPCTSTR)"*.bdjf");
    return 0;
}

bool searchDrive(LPCTSTR lpFolder, LPCTSTR lpFilePattern)
{

   TCHAR  szFullPattern[MAX_PATH];

   WIN32_FIND_DATA FindFileData;

   HANDLE hFile = INVALID_HANDLE_VALUE;

   PathCombine(szFullPattern, lpFolder, L"x");

   MessageBox(NULL,szFullPattern,lpFilePattern,MB_ICONWARNING | 
                                               MB_CANCELTRYCONTINUE | 
                                               MB_DEFBUTTON2);

   HANDLE hFind = FindFirstFile(szFullPattern, &FindFileData);

I'm using Visual Studio 2008.

在此处输入图片说明

As you can see all except but the last character and the '\\' can't be seen, the the rest have come out in Asian characters.

(NOTE don't worry about any of the other issues with my code.)

Any ideas on why this is happening would be appreciated.

Here's your problem:

searchDrive((LPCTSTR)"C:\\",(LPCTSTR)"*.bdjf");

By default, Visual Studio compiles programs in Unicode mode. So you're casting both of the "ANSI" (8-bit characters) strings to "Unicode" (16-bit character) string type.

This doesn't convert the strings. It just tells the compiler to pretend that they were Unicode strings all along. It's hardly surprising that this doesn't work; the upshot is that each pair of ANSI characters is treated as a single Unicode character.

You can fix the problem like this:

searchDrive(TEXT("C:\\"), TEXT("*.bdjf"));

But unless you have a specific reason to support ANSI mode, it would be better still to use

searchDrive(L"C:\\", L"*.bdjf");

and change the declaration of searchDrive to use LPCWSTR instead of LPCTSTR .

Change this line:

searchDrive((LPCTSTR)"C:\\",(LPCTSTR)"*.bdjf");

To this:

searchDrive(L"C:\\", L"*.bdjf");

You can also say TEXT("C:\\\\") and TEXT("*.bdjf") to do the appropriate string literal conversion.

But in general, you should just stop using TCHAR and just use Unicode and long strings everywhere.

Please remove all casts where you don't know exactly what you are doing and can explain why the cast is neccessary for correct working. Never muzzle the compiler, instead ask it to speak up: Use -Wall -Wextra , and handle all warnings appropriately.

Doing so will make the error glaringly obvious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM