您的位置:首页 > 编程语言 > C语言/C++

C++中获得文件大小

2011-07-20 13:58 351 查看
#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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: