c ++检查文件是否为空

时间:2010-11-02 13:57:26

标签: c++ file winapi

我有一个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 );

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

谢谢,
ILE

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

在打开文件之前,您可以尝试:

WIN32_FIND_DATA wfd;
HANDLE h = FindFirstFile(filename, &wfd);
if (h != INVALID_FILE_HANDLE)
{
    // file exists
    if (wfd.nFileSizeHigh != 0 || wfd.nFileSizeLow != 0)
    {
        // file is not empty
    }
    FindClose(h)
}