您的位置:首页 > 其它

编写测试:VC下获取文件大小的4种方法

2013-02-25 16:56 471 查看
代码参考自lailx的博客:获取文件大小的4种方法(/article/7186559.html

// 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()返回的文件大小是固定不变的,因此在需要监视文件大小时,这两种方法不可取。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: