c ++检查文件是否为空

ili*_*ica 1 c++ winapi file

我有一个C++项目需要编辑.这是变量的声明:

// Attachment
    OFSTRUCT ofstruct;
    HFILE hFile = OpenFile( mmsHandle->hTemporalFileName , &ofstruct , OF_READ );
    DWORD hFileSize = GetFileSize( (HANDLE) hFile , NULL );
    LPSTR hFileBuffer = (LPSTR)GlobalAlloc(GPTR, sizeof(CHAR) * hFileSize );
    DWORD hFileSizeReaded = 0;
    ReadFile( (HANDLE) hFile , hFileBuffer, hFileSize, &hFileSizeReaded, NULL );
    CloseHandle( (HANDLE) hFile );
Run Code Online (Sandbox Code Playgroud)

我需要检查文件是否附加(我想我需要检查hFile是否有任何值),但不知道如何.我尝试过,hFile == NULL但这不起作用.

谢谢,
Ile

Mic*_*eyn 6

将hFile与HFILE_ERROR进行比较(不是NULL!).此外,您应该将OpenFile更改为CreateFile并正确调用它,OpenFile早已被弃用.实际上MSDN明确指出:

OpenFile功能

仅在16位版本的Windows中使用此功能.对于较新的应用程序,请使用CreateFile函数.

当您进行此更改时,您将获得一个HANDLE,您应该将其与INVALID_HANDLE_VALUE进行比较.

更新:获取文件大小的正确方法:

LARGE_INTEGER fileSize={0};

// You may want to use a security descriptor, tweak file sharing, etc...
// But this is a boiler plate file open
HANDLE hFile=CreateFile(mmsHandle->hTemporalFileName,GENERIC_READ,0,NULL,
                        OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);

if (hFile!=INVALID_HANDLE_VALUE && GetFileSizeEx(hFile,&fileSize) && 
    fileSize.QuadPart!=0)
{
  // The file has size
}
else
{
  // The file is missing or size==0 (or an error occurred getting its size)
}

// Do whatever else and don't forget to close the file handle when done!
if (hFile!=INVALID_HANDLE_VALUE)
  CloseHandle(hFile);
Run Code Online (Sandbox Code Playgroud)