1. 叙述
对于读取本地文件,很多时候需要预先知道本地文件的大小在进行读取。网上给出的方案是移动文件指针,计算文件头和文件尾的偏移,计算出文件的大小。但是我总觉得这样做可能会与读取文件一样消耗性能,为了解决这个问题,我写了如下例子验证了一下。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
#include <iostream> #include <fstream> #include<Windows.h> using namespace std; class CTimer { public : CTimer( void ); ~CTimer( void ); int time_in(); double time_out(); private : LARGE_INTEGER litmp; LONGLONG qt1, qt2; double dft, dff, dfm; }; CTimer::CTimer( void ) { } CTimer::~CTimer( void ) { } int CTimer::time_in() { QueryPerformanceFrequency(&litmp); //获得时钟频率 dff = ( double )litmp.QuadPart; QueryPerformanceCounter(&litmp); //获得初始值 qt1 = litmp.QuadPart; return 1; } double CTimer::time_out() { QueryPerformanceCounter(&litmp); //获得终止值 qt2 = litmp.QuadPart; dfm = ( double )(qt2 - qt1); dft = dfm / dff; //获得对应的时间值 return dft; } int main() { string file_name = "D:/Work/test.zip" ; CTimer timer; ifstream ifs(file_name, std::ios::binary | std::ios::in); if (!ifs.is_open()) { return 0; } timer.time_in(); ifs.seekg(0, std::ios::end); int len = ifs.tellg(); ifs.seekg(0, std::ios::beg); cout << "获取文件长度耗时:" << timer.time_out() << "秒" << endl; timer.time_in(); char *buff = new char [len]; ifs.read(buff, len); delete []buff; timer.time_out(); cout << "读取文件耗时:" << timer.time_out() << "秒" << endl; return 1; } |
如上所示,我写了一个计时器,分别统计偏移文件指针计算文件长度与读取整个文件的耗时,运行结果如下:
2. 结论
可以看到,偏移文件指针带来的时间消耗非常小,几乎可以忽略不记。通过这个方法,不仅可以很快计算文件长度,还可以根据需要读取文件的特定位置,从而达到节省性能的目的。
到此这篇关于C++通过文件指针获取文件大小的方法实现的文章就介绍到这了,更多相关C++ 文件指针获取文件大小内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/charlee44/p/15487967.html