維尼的蜂巢

RealTime??!! It’s amazing!!!!

Get File Size… 八月 29, 2008

Filed under: VC++/C++/C — kevinlin @ 3:54 下午

取得檔案大小還蠻重要的,但是一般取得頂多只能2GB,超過2GB的檔案要怎麼辦??
下面的方法1~3可正確取得2GB以下的FileSize,4跟5兩種方法可以正確取得2GB以上的FileSize

method1

unsigned long  GetFileLength( FILE * fileName)
{
     unsigned long pos = ftell(fileName);
     unsigned long len = 0;   
     fseek ( fileName, 0L, SEEK_END );
     len = ftell ( fileName );
     fseek ( fileName, pos, SEEK_SET );
     return len;
}

method2

unsigned long  GetFileLength( char * fileName)
{
    struct stat buf;
    int i = stat ( fileName, &buf );
    if (i !=0)
       MessageBox(NULL,"ERROR for STAT","ERROR",0);
    return buf.st_size;
}

method3

long GetFileLength(char *fileName)
{
        int fd = open(fileName,O_RDONLY | O_BINARY);
        if(fd == -1 ) return -1;
        long lsize = filelength(fd);
        close(fd);
        return lsize;
}

method4
利用Windows API GetFileSize & GetFileSizeEx
範例參考http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/getfilesize.asp
Large File Size 請使用 GetFileSizeEx函式。

method5
利用Windows API FindFirstFile()

#include <windows.h>
double dblFileSize(const char* fname)
{
  if (!fname && !*fname)
     return 0.0;
  HANDLE h;
  WIN32_FIND_DATA info;

  if ((h=FindFirstFile(fname,&info)) 
      != INVALID_HANDLE_VALUE)
  {
     FindClose(h);
     if ((info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
         == 0) // Is it a file?
     {
        union
        {
          struct { DWORD low, high; } lh;
          __int64 size; // MS large int extension
        } file;
        file.lh.low = info.nFileSizeLow;
        file.lh.high= info.nFileSizeHigh;
        return file.size; // will be casted to double
     }
     // It's a directory, not a file
  }
  return 0.0; // No such name.
}

參考:http://www.tek-tips.com/viewthread.cfm?qid=1080801&page=6

 

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s