编写测试:VC下获取文件大小的4种方法
2013-02-25 16:56
471 查看
代码参考自lailx的博客:获取文件大小的4种方法(/article/7186559.html)
测试结果:
当目标文件正在被写入的时候,体积逐渐增大,但测试发现第GetFileSize2()、GetFileSize4()返回的文件大小是固定不变的,因此在需要监视文件大小时,这两种方法不可取。
// TestGetFileSize.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <windows.h> #include <io.h> #include <sys\stat.h> using namespace std; size_t GetFileSize1(LPCTSTR lpszFileName) { size_t nResult = 0; HANDLE handle = CreateFile(lpszFileName, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); if (handle != INVALID_HANDLE_VALUE) { nResult = GetFileSize(handle, NULL); CloseHandle(handle); } return nResult; } size_t GetFileSize2(LPCTSTR lpszFileName) { size_t nResult = 0; WIN32_FIND_DATA fileInfo; HANDLE hFind; hFind = FindFirstFile(lpszFileName, &fileInfo); if(hFind != INVALID_HANDLE_VALUE) nResult = fileInfo.nFileSizeLow; FindClose(hFind); return nResult; } size_t GetFileSize3(LPCTSTR lpszFileName) { size_t nResult = 0; FILE* file = fopen(lpszFileName, "r"); if (file) { nResult = filelength(fileno(file)); fclose(file); } return nResult; } size_t GetFileSize4(LPCTSTR lpszFileName) { size_t nResult = 0; struct _stat info; _stat(lpszFileName, &info); nResult = info.st_size; return nResult; } DWORD Test(size_t (*pFunc)(LPCTSTR), LPCTSTR lpszFileName) { DWORD dwResult = 0; size_t nFileSize = 0; DWORD tick = GetTickCount(); for (int i=0; i<10000; i++) { nFileSize = pFunc(lpszFileName); // cout<<"FileSize = "<<nFileSize<<endl; } dwResult = GetTickCount() - tick; cout<<"Cost: "<<dwResult<<endl; return dwResult; } int main(int argc, char* argv[]) { char *szFileName = "G:\\1.txt"; DWORD dwCost[4] = {0}; dwCost[0] = Test(GetFileSize1, szFileName); system("pause"); dwCost[1] = Test(GetFileSize2, szFileName); system("pause"); dwCost[2] = Test(GetFileSize3, szFileName); system("pause"); dwCost[3] = Test(GetFileSize4, szFileName); system("pause"); return 0; }
测试结果:
当目标文件正在被写入的时候,体积逐渐增大,但测试发现第GetFileSize2()、GetFileSize4()返回的文件大小是固定不变的,因此在需要监视文件大小时,这两种方法不可取。
相关文章推荐
- VC C/C++ 4种方法获取文件大小 Windows API
- VC C/C++ 4种方法获取文件大小 Windows API
- VC C/C++ 4种方法获取文件大小 Windows API
- VC 获取文件大小方法集锦
- VC获取文件大小的方法
- VC 获取文件大小方法集锦
- VC获取文件大小的方法
- VC++实现获取文件占用空间大小的两种方法(非文件大小)
- WINDOWS 下 VC获取文件大小的几种方法(转)
- VC++实现获取文件占用空间大小的两种方法(非文件大小)
- VC++实现获取文件占用空间大小的两种方法(非文件大小)
- VC获取文件大小的方法
- 获取文件大小的几种方法
- Java中获取文件大小的正确方法
- PHP获取文件扩展名的4种方法
- C/C++获取文件大小的多种方法
- [Android Pro] 关于inputStream.available()方法获取文件的总大小
- linux获取文件大小的几种方法
- Java中获取文件大小的正确方法
- C/C++多种方法获取文件大小(转)