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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值