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