C++通过文件指针获取文件大小

1. 叙述

对于读取本地文件,很多时候需要预先知道本地文件的大小在进行读取。网上给出的方案是移动文件指针,计算文件头和文件尾的偏移,计算出文件的大小。但是我总觉得这样做可能会与读取文件一样消耗性能,为了解决这个问题,我写了如下例子验证了一下。

#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;
}

如上所示,我写了一个计时器,分别统计偏移文件指针计算文件长度与读取整个文件的耗时,运行结果如下:

imglink1

2. 结论

可以看到,偏移文件指针带来的时间消耗非常小,几乎可以忽略不记。通过这个方法,不仅可以很快计算文件长度,还可以根据需要读取文件的特定位置,从而达到节省性能的目的。

原文地址:https://www.cnblogs.com/charlee44/p/15487967.html