unsigned long GetFileLength1 (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; }
<方法二>利用stat
unsigned long GetFileLength2 (char * fileName) { struct stat buf; int i = stat ( fileName, &buf ); if (i !=0) MessageBox(NULL,"ERROR for STAT","ERROR",0); return buf.st_size; }
<方法三>利用filelength 必須include< fcntl.h>
原型: long filelength(int fd)
long GetFileLength3(char *fileName)
{
int fd = open(fileName,O_RDONLY | O_BINARY);
if(fd == -1 ) return -1;
long lsize = filelength(fd);
close(fd);
return lsize;
}
<方法四> 利用Windows API GetFileSize & GetFileSizeEx
Large File Size 請使用 GetFileSizeEx函式。
<方法五>利用Windows API FindFirstFile()
/// For Windows:
#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. }方法 1~3都無法處理大檔案,要注意~
資料來源參考:這裡