Domanda

I just want to read a file using the function CreateFile such as following :

#include <iostream>
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv)
{
    PIMAGE_DOS_HEADER pImageDosHeader;
    HANDLE hFile = NULL;
    HANDLE hMapObject;
    PUCHAR uFileMap;
    if (argc < 2)
        return (-1);
    std::cout << "hFile=" << hFile << std::endl;
    if (!(hFile = CreateFile((LPCWSTR)argv[1], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
        NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)))
    {
        return (-1);
    } else {
        std::cout << argv[1] << std::endl;
        std::cout << "hFile=" << hFile << std::endl;
        getchar();
    }
    return (0);
}

The problem is that the output is like below :

hFile=000000 (the pointer is initialized to NULL -> OK)

hFile=FFFFFF (invalid pointer)

Does anyone can help me, please ? Thanks in advance for your help.

È stato utile?

Soluzione

The following:

if (!(hFile = CreateFile(...)))

is not how you check for errors.

From the documentation:

If the function fails, the return value is INVALID_HANDLE_VALUE. To get extended error information, call GetLastError.

INVALID_HANDLE_VALUE is -1, or 0xFFFFFFFFF in hex. You need to call GetLastError() to find out what happened.

Altri suggerimenti

When you get an error from most Win32 APIs, you can call GetLastError() to find out what went wrong. Take it from there.

This type of defensive programming is essential for productive Win32 programming. The actual conditions for a failure vary by API, so use MSDN to check what you should be looking for in your failure codepaths.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top