Alexander Mashin
Alexander Mashin

Reputation: 49

CreateFile() returns INVALID_HANDLE_VALUE (C++)

Consider:

void main()
{
    LPSTR FileName;
    FileName = "C:\\test2.wav";
    hFile = CreateFile((LPCWSTR)FileName, GENERIC_READ, 0, 0,
                       OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, 0);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        cout << "INVALID_HANDLE_VALUE" << endl;
        return;
    }
}

This program always prints "INVALID_HANDLE_VALUE". Why? File C:\test2.wav exists.

Upvotes: 1

Views: 19796

Answers (2)

Cornstalks
Cornstalks

Reputation: 38238

You can't just cast a multibyte/ASCII/UTF-8 string to a wide/UTF-16 string. You actually have to convert it. Try using MultiByteToWideChar() to convert it. The other answers talking about the different versions of CreateFile are probably simplest, but just in case you actually need wide character strings this can be useful to know.

Upvotes: 1

john
john

Reputation: 88027

You misunderstand how casting works. What you are saying to the compiler is to pretend that FileName is a wide string, but it isn't so your code fails. Two solutions

1) Use the right kind of string (a wide string in your case)

LPTSTR FileName;
FileName = _T("c:\\test2.wav");
hFile = CreateFile(FileName, GENERIC_READ, 0 , 0,
    OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, 0);

2) Use the version of CreateFile (called CreateFileA) that requires a narrow string

LPSTR FileName;
FileName = "c:\\test2.wav";
hFile = CreateFileA(FileName, GENERIC_READ, 0 , 0,
    OPEN_EXISTING, FILE_ATTRIBUTE_ARCHIVE, 0);

It's a common feature of newbie code that it has casts all over the place. Try to avoid casting as it often just hides errors (like your cast did). This is especially true if you don't understand how casts work. Unfortunately it's not possible to do Windows programming without a certain number of casts.

Upvotes: 8

Related Questions