第二十一章流 6检查文件是否打开 简单

//第二十一章流 6检查文件是否打开
// 
// 使用布尔函数eof() bad() fail()他good()够检查
// eof()/bad()/fail()返回假时或者 good()返回真时文件打开成功
/*#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ofstream fout("a.txt");
	fout<<"输出到文件";
	fout.close();

	ifstream fin("a.txt");
	if(fin.good()){ //可将fin.good()可替换为fin
	   cout<<"打开文件成功,以下是文件内容:"<<endl;
	   char ch;
	   while(!fin.eof()) //未到文件尾时循环
	   {
	        ch = fin.get();
			cout<<ch;
	   }
	}
	fin.close();
	fin.open("bb.txt");
	if(fin.fail()){
	   cout<<"文件打开失败"<<endl;
	}
	fin.close();

    return 0;
}
*/

//is_open()方法打开文件
/*#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ofstream fout("a.txt");
	if(fout){
	    fout<<"输出到文件\n";
	}
	fout.close();

	ifstream fin("a.txt");
	if(fin){
	    cout<<"打开文件成功,以下是文件内容"<<endl;
		char ch;
		while(fin.get(ch))
		{
		   cout<<ch;
		}
	}
	fin.close();

	fout.open("a.txt",ios::app);
	if(fout.is_open()){
	   fout<<"再次输入到文件中\n";
	}
	fout.close();
	fin.close();
	fin.open("a.txt");
	if(fin.is_open())
	{
	   cout<<"打开文件成功,以下是文件内容:"<<endl;
	   char ch;
	   while(!fin.eof())
	   {
		   ch = fin.get();
		   cout<<ch;
	   }
	}
	fin.close();
    return 0;
}*/

  

原文地址:https://www.cnblogs.com/xiangxiaodong/p/2709698.html