转自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{...//读出} 谢谢以上两位原作者的分析!

评论