C++中获得文件大小

 

#include <fstream>

using namespace std;

int main(int argc, char* argv[])

{

ifstream in("file.txt");

in.seekg(0, ios::end); //设置文件指针到文件流的尾部

streampos ps = in.tellg(); //读取文件指针的位置

cout << "File size: " << ps << endl;

in.close(); //关闭文件流

return 0;

}

另一种方法:

对文件操作时有时获得文件的大小时必要的.下面是获得其大小小的较简单方法.
#include<io.h> //C语言头文件
#include<iostream> //for system();
using namespace std;
int main()
{
int handle;
handle = open("test.txt", 0x0100); //open file for read
long length = filelength(handle); //get length of file
cout<<"file length in bytes:"<<length<<endl;
close(handle);

system("pause");
return 0;
}

常用的C语言方法:

将文件打开调整文件指针到文件尾,返回值即位文件大小!
#include <iostream.h>
#include <stdio.h>
void main
{
FILE *fp;
char fileName[100];

cin>>fileName;
fp=fopen(fileName,"r");

long int fileLength=fseek(fp,0L,SEEK_END);
cout<<fileLength;

fclose(fp);
}

类似的方法:

#include <iostream> // not needed for many systems
#include <fstream>
#include <string>

using namespace std;

int main()
{
string inputfilename;
cout << "Enter name for inputfile: ";
cin >> inputfilename;
cout<<endl;
ifstream fin(inputfilename.c_str());

if(!fin.is_open())
{
cout<<"input file open error"<<endl;
return -1;
}

fin.seekg(0,ios::end);

streampos ps = fin.tellg();
cout<<"File size is "<<ps<<endl;
fin.close();

return 0;
}

From: http://blog.163.com/hduzhang@126/blog/static/310119172007621104355371/

原文链接: https://www.cnblogs.com/wangicter/archive/2011/07/20/4767467.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++中获得文件大小

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/29026

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月8日 上午6:26
下一篇 2023年2月8日 上午6:26

相关推荐