How get file size? Open with CreateFile() returns INVALID when file is open by another appl.


  • I need to get the size of some disk files.  I've been using the following code successfullly:

         HANDLE fileHandle = CreateFile(c_str(), GENERIC_READ,
         if (fileHandle != INVALID_HANDLE_VALUE) {
                LARGE_INTEGER sizeStruct;
                BOOL success =  GetFileSizeEx(

    But the above call to CreateFile() returns INVALID_HANDLE_VALUE when the requested file (which exists) is open for write by another application.  The error message from GetLastError says "cannot open because file is in use by another appl".   My question is:

    Is there a way to get CreateFile() to successfully open the file, even when it is open by another application?  and if not, is there another way to get the size of a file without opening it?

    Thanks in advance,

    Thursday, October 09, 2008 2:41 PM


All replies

  • Please give us more if the file is in write mode by other application if you get file size and it will be invalid due to change in file size.  Is that console or windows application ?
    Thursday, October 09, 2008 3:01 PM

  • #include
    #include <sys\stat.h>

    __int64 FileSize64( const char * szFileName )
    struct __stat64 fileStat;
    int err = _stat64( szFileName, &fileStat );
    if (0 != err) return 0;
    return fileStat.st_size;

    Check this link

    • Marked as answer by noleander Thursday, October 09, 2008 11:16 PM
    Thursday, October 09, 2008 3:09 PM

  • _findfirst/_findnext return a _finddata_t structure which has a file size member.
    Also see _wfindfirst, _findfirst32, _wfindfirst32, _findfirst64, etc., etc.

    Also see FindFirstFile in the Win32 API which returns a WIN32_FIND_DATA
    structure which provides file size info. Also see FindFirstFileEx, etc.

    - Wayne

    Thursday, October 09, 2008 3:19 PM