正文

标准C++获取文件长度的方法2008-04-02 11:26:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/aurora/33823.html

分享到:

转自http://groups.google.com/group/bruceteen/browse_thread/thread/90ef833dfbad9ab6 #include <fstream> #include <cstdio> using namespace std; int main( void ) {     fstream file( "D:\\张国荣.JPG", ios_base::binary | ios_base::in );     if( file.is_open() )     {         // ... // 这里可以进行其它操作         fstream::pos_type cur_pos = file.tellg();         file.seekg( 0L, ios::end );         fstream::pos_type end_pos = file.tellg();         file.seekg( cur_pos, ios::beg );         streamoff flen = end_pos; // 注1         printf( "%I64d\n", flen );     }     return 0; } // 注1: 在gcc3.4.2中 streamoff 是 int64_t. //      而在VC++6.0中 streamoff 是 long, 所以除了标准的 //      operator fposstreamoff() const 外, 又提供了一个 //      fpos_t get_fpos_t() const, fpos_t 是 __int64. 补充] #include <iostream> #include <fstream> using namespace std; fpos_t filelen( ifstream& file ) {     fstream::pos_type cur_pos = file.tellg();     file.seekg( 0L, ios::end );     fstream::pos_type end_pos = file.tellg();     file.seekg( cur_pos, ios::beg );     return end_pos.seekpos(); } int main( void ) {     ifstream infile( "s.dat" );     if( infile.is_open() )     {         fpos_t len = filelen( infile );         cout << "文件长度" << len << endl;     }     else     {         cout << "文件不存在" << endl;     } }   下面转自:http://blog.programfan.com/article.asp?id=20714 //判断文件是否为空 //严重有问题啊,把写好的文件 换行就不行了。#include   <iostream>  #include <string> #include   <fstream>  #include <cstdlib> using   namespace   std;   int   main()   {    ifstream   input("E:\\a.txt");       if(input) {  string s;  getline(input,s);  if(s=="")  {   cout<<"空文件 "<<endl;   input.close();   ofstream output("E:\\a.txt");   output<<"sadfd"<<endl;   output.close();  }  else  {   ifstream output("E:\\a.txt");   while(getline(output,s))    cout<<s<<endl;  }   }   }   网上找的类似的问题:#include   <iostream>     #include   <fstream>     using   namespace   std;     int   main()     {     ifstream   input("a.txt");     if(input){     input.seekg(0,ios_base::end);     fstream::off_type   Len=input.tellg();     if(Len==0)   cout<<"Empty   file\n";     }     }   streamoff filelen( ifstream& file )  //判断文件是否为空 {    fstream::pos_type cur_pos = file.tellg();    file.seekg( 0L, ios::end );    fstream::pos_type end_pos = file.tellg();    file.seekg( cur_pos, ios::beg );    return end_pos;}len = filelen( infile );if(0==len)//判断是否文件为空{...//写入}else{...//读出} 谢谢以上两位原作者的分析!

阅读(12798) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册