出发点:及时释放文件资源
例子:ofstream 文件输出流 和 RAII 的结合
#include <bits/stdc++.h>
#define rep( i , j , n ) for ( int i = int(j) ; i < int(n) ; ++i )
#define dew( i , j , n ) for ( int i = int(n-1) ; i > int(j) ; --i )
#define _PATH __FILE__ , __LINE__
typedef std::pair < int , int > P ;
using std::cin ;
using std::cout ;
using std::endl ;
using std::string ;
static std::atomic_int cnt{ 0 } ;
namespace YHL {
// 模拟 boost::nocopyable 不可复制
class Noncopyable {
public:
Noncopyable() = default ;
~Noncopyable() = default ;
private:
Noncopyable(const Noncopyable&) = delete ;
Noncopyable& operator=(const Noncopyable&) = delete ;
} ;
}
class myFile : private YHL::Noncopyable {
private:
// 文件输出流
std::ofstream fileHandle ;
myFile(const myFile&) = delete ;
myFile& operator=(const myFile&) = delete ;
public:
myFile() = default ;
explicit myFile(const char* fileName) {
fileHandle.open(fileName, std::ios::app) ;
if ( !fileHandle.good() )
throw std::runtime_error("文件打开失败");
}
~myFile() {
// RAII 局部对象自动调用析构函数关闭文件输出流
if( fileHandle.is_open() ) {
fileHandle.close() ;
cout << "析构函数关闭文件输出流" << endl ;
}
}
bool writeFile(const char *str) {
try {
if ( !fileHandle.is_open() )
throw std::runtime_error("文件尚未打开") ;
} catch ( std::exception &e ) {
cout << e.what() << endl ;
cout << "fileName : " ;
string fileName ;
cin >> fileName ;
fileHandle.open(fileName, std::ios::app) ;
}
try {
if ( !fileHandle.is_open() )
throw std::runtime_error("文件写入失败") ;
} catch ( std::exception &e ) {
cout << e.what() << endl ; return false ;
}
fileHandle << str ;
return true ;
}
bool writeFile(const char *fileName, const char *str) {
if( fileHandle.is_open() )
fileHandle.close() ;
fileHandle.open(fileName, std::ios::app) ;
try {
if ( !fileHandle.is_open() )
throw std::runtime_error("文件写入失败") ;
} catch ( std::exception &e ) {
cout << e.what() << endl ; return false ;
}
fileHandle << str ;
return true ;
}
} ;
int main () {
myFile example("RAII(1).txt") ;
example.writeFile("I love You forever") ;
example.writeFile("RAII(2).txt", "In the rest of my life") ;
myFile example2 ;
example2.writeFile("if you would like to") ;
return 0 ;
}