优先使用fstream::operator!()而不是fstream::is_open()(6894)

判断fstream是否可以继续操作应当使用bool operator!() const而不是is_open,因为is_open只表示是否已经打开,而不论其是否正确。

#pragma warning( disable: 4786 )
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int main( void )
{
    ostream_iterator<char> oite( cout );

    ifstream file( "D://test.txt" );
    cout << "文件是否打开:" << boolalpha << bool(file.is_open()) << ' ';
    cout << "文件是否正确:" << boolalpha << !!file << endl;
    {
        file.seekg( 0L, ios::beg );
        istream_iterator<char> fitor( file );
        istream_iterator<char> fend;
        copy( fitor, fend, oite );
        cout << endl;
    }
    cout << "文件是否打开:" << boolalpha << bool(file.is_open()) << ' ';
    cout << "文件是否正确:" << boolalpha << !!file << endl;
    {
        file.seekg( 0L, ios::beg );
        istream_iterator<char> fitor( file );
        istream_iterator<char> fend;
        copy( fitor, fend, oite );
        cout << endl;
    }
    return 0;
}

输出是:
文件是否打开:true 文件是否正确:true
……文件内容……
文件是否打开:true 文件是否正确:false
……本来应该打印文件内容,但因为file不正确了,所以只输出空行……
Press any key to continue

 

 

 

 

PS:

warning C4786错误解决方法:
此warning产生的原因是因为标识符过长,超过了最大限定255个字。

解决方法有两种,一种是直接定义别名:
#ifdef _DEBUG
#define VeryLongClassNameA A
#define VeryLongClassNameB B
#endif

另一种是屏蔽4786warning:
#pragma warning(disable : 4786)

注意屏蔽语句必须放在报错的模板类的引用声明(如#include <vector>)之前,否则还是不起作用。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值