编写测试:VC下获取文件大小的4种方法
生活随笔
收集整理的這篇文章主要介紹了
编写测试:VC下获取文件大小的4种方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼參考自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 }
測試結果:
轉載于:https://www.cnblogs.com/ddgg/archive/2013/02/25/2932335.html
總結
以上是生活随笔為你收集整理的编写测试:VC下获取文件大小的4种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MESSL(maven + extjs
- 下一篇: s3c2440移植MQTT