前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++通过文件指针获取文件大小

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

作者头像
charlee44
发布2021-11-02 16:55:15
2.8K0
发布2021-11-02 16:55:15
举报
文章被收录于专栏:代码编写世界代码编写世界

目录

1. 叙述

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

代码语言:javascript
复制
#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
imglink1

2. 结论

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-10-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 叙述
  • 2. 结论
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档