#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;
// 而在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();
{
ifstream infile( "s.dat" );
if( infile.is_open() )
{
fpos_t len = filelen( infile );
cout << "文件长度" << len << endl;
}
else
{
cout << "文件不存在" << endl;
}
//判断文件是否为空 //严重有问题啊,把写好的文件 换行就不行了。
#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
{
...//读出
}
谢谢以上两位原作者的分析!
评论