I am trying to get information of existing file using GetFileInformationByHandle(). My function that performs the required task receives LPCTSTR Filename as argument. Here is the code:

getfileinfo(LPCTSTR Filename)
{
    OFSTRUCT oo;
    BY_HANDLE_FILE_INFORMATION lpFileInformation;
    HFILE hfile=OpenFile((LPCSTR)Filename,&oo,OF_READ);
    int err=GetLastError();
    GetFileInfomationByHandle((HANDLE)hfile,&lpFileInformation);
}

Above code works fine if I declare Filename as LPCSTR but as per requirement of my function I receive the filename in LPCTSTR so if I use typecasting then openfile() cannot find the specified file and returns -1.

Can anyone tell me how to get file information if filename is LPCTSTR? Or how to convert LPCTSTR to LPCSTR.

Why is this typecasting not working? I believe this should work.

有帮助吗?

解决方案 2

The solution to your immediate problem is to replace OpenFile() with CreateFile(), just like the OpenFile() documentation says to do:

Note This function has limited capabilities and is not recommended. For new application development, use the CreateFile function.

For example:

getfileinfo(LPCTSTR Filename)
{
    HANDLE hFile = CreateFile(FileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        int err = GetLastError();
        // handle error as needed ...
    }
    else
    {
        BY_HANDLE_FILE_INFORMATION FileInfo = {0};
        BOOL ok = GetFileInformationByHandle(hFile, &FileInfo);
        int err = GetLastError();
        CloseHandle(hFile);

        if (!ok)
        {
            // handle error as needed ...
        }
        else
        {
            // use FileInfo as needed...
        }
    }
}

That being said, a better solution is to not open the file at all. Most of the information that GetFileInformationByHandle() returns can be obtained using FindFirstFile() instead:

getfileinfo(LPCTSTR Filename)
{
    WIN32_FIND_DATA FileData = {0};
    HANDLE hFile = FindFirstFile(Filename, &FileData);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        int err = GetLastError();
        // handle error as needed ...
    }
    else
    {
        FindClose(hFile);
        // use FileData as needed ...
    }
}

其他提示

Just casting the pointer doesn't change the actual data (ie filename) that is being pointed to into eight-bit characters.

Reading the docs at MSDN suggests using CreateFile instead, which handles LPCTSTR filenames.

Have a look at Project Properties/Configuration Properties/General/Character Set. This is normally set to UNICODE. It can be changed to MBCS.

If it is set to MBCS, then the code does not need to be modified.

If it is set to Unicode, which I suspect it is otherwise you won't be asking this question, use widechartomultibyte to convert it from LPCTSTR (const wchar_t*) to LPSTR (const char*).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top