Repository navigation
Expand file tree
/
Copy pathfileHandle.cpp
More file actions
60 lines (49 loc) · 1.46 KB
/
Copy pathfileHandle.cpp
File metadata and controls
60 lines (49 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>
#include <fstream>
#include <exception>
class FileHandle{
private:
std::ofstream filestream;
std::string filename;
public:
FileHandle(const std::string& name) : filename(name){
filestream.open(filename);
if(!filestream.is_open()){
throw std::runtime_error("Could not open file: "+filename);
}
std::cout<<"[RAII] File "<<filename<<" opened.\n";
}
FileHandle(FileHandle&& other)noexcept :
filestream(std::move(other.filestream)),
filename(std::move(other.filename)){
std::cout<<"[RAII] Moved ownership from "<<filename<<"\n";
}
~FileHandle(){
if(filestream.is_open()){
filestream.close();
std::cout<<"[RAII] File "<<filename<<" closed automatically.\n";
}
}
void write(const std::string& text){
filestream<<text<<std::endl;
}
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
};
void processFile(){
FileHandle myFile("test.txt");
myFile.write("Hello RAII....");
std::cout<<"Simulating an error...\n";
throw std::runtime_error("Something went wrong! In process.");
myFile.write("This will never be written");
}
int main(){
try{
processFile();
}catch(const std::exception& e){
std::cout<< "Caught exception: " << e.what() << "\n";
}
std::cout<<"Program continues safely.\n";
return 0;
}