判断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>)之前,否则还是不起作用。