游戏开发论坛

 找回密码
 立即注册
搜索
查看: 1342|回复: 0

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

[复制链接]

1367

主题

1993

帖子

2118

积分

金牌会员

Rank: 6Rank: 6

积分
2118
发表于 2004-11-19 20:17:00 | 显示全部楼层 |阅读模式
判断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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

作品发布|文章投稿|广告合作|关于本站|游戏开发论坛 ( 闽ICP备17032699号-3 )

GMT+8, 2025-12-23 09:01

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表