代码参考自lailx的博客:获取文件大小的4种方法(http://www.cnblogs.com/lailx/archive/2011/11/20/2256550.html)
1 // TestGetFileSize.cpp : Defines the entry point for the console application. 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <windows.h> 7 #include <io.h> 8 #include <sys\stat.h> 9 10 using namespace std; 11 12 size_t GetFileSize1(LPCTSTR lpszFileName) 13 { 14 size_t nResult = 0; 15 HANDLE handle = CreateFile(lpszFileName, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); 16 if (handle != INVALID_HANDLE_VALUE) 17 { 18 nResult = GetFileSize(handle, NULL); 19 CloseHandle(handle); 20 } 21 return nResult; 22 } 23 24 size_t GetFileSize2(LPCTSTR lpszFileName) 25 { 26 size_t nResult = 0; 27 WIN32_FIND_DATA fileInfo; 28 HANDLE hFind; 29 hFind = FindFirstFile(lpszFileName, &fileInfo); 30 if(hFind != INVALID_HANDLE_VALUE) 31 nResult = fileInfo.nFileSizeLow; 32 FindClose(hFind); 33 return nResult; 34 } 35 36 size_t GetFileSize3(LPCTSTR lpszFileName) 37 { 38 size_t nResult = 0; 39 FILE* file = fopen(lpszFileName, "r"); 40 if (file) 41 { 42 nResult = filelength(fileno(file)); 43 fclose(file); 44 } 45 return nResult; 46 } 47 48 size_t GetFileSize4(LPCTSTR lpszFileName) 49 { 50 size_t nResult = 0; 51 struct _stat info; 52 _stat(lpszFileName, &info); 53 nResult = info.st_size; 54 return nResult; 55 } 56 57 DWORD Test(size_t (*pFunc)(LPCTSTR), LPCTSTR lpszFileName) 58 { 59 DWORD dwResult = 0; 60 size_t nFileSize = 0; 61 DWORD tick = GetTickCount(); 62 for (int i=0; i<10000; i++) 63 { 64 nFileSize = pFunc(lpszFileName); 65 // cout<<"FileSize = "<<nFileSize<<endl; 66 } 67 dwResult = GetTickCount() - tick; 68 cout<<"Cost: "<<dwResult<<endl; 69 return dwResult; 70 } 71 72 73 int main(int argc, char* argv[]) 74 { 75 char *szFileName = "G:\\1.txt"; 76 DWORD dwCost[4] = {0}; 77 78 dwCost[0] = Test(GetFileSize1, szFileName); 79 system("pause"); 80 81 dwCost[1] = Test(GetFileSize2, szFileName); 82 system("pause"); 83 84 dwCost[2] = Test(GetFileSize3, szFileName); 85 system("pause"); 86 87 dwCost[3] = Test(GetFileSize4, szFileName); 88 system("pause"); 89 90 return 0; 91 }
测试结果:
当目标文件正在被写入的时候,体积逐渐增大,但测试发现第GetFileSize2()、GetFileSize4()返回的文件大小是固定不变的,因此在需要监视文件大小时,这两种方法不可取。