forked from furkankirac/cs409-2023-24-spring
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek15-app3.cpp
36 lines (28 loc) · 829 Bytes
/
week15-app3.cpp
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
// RAII (Resource Acquisition is Initialization)
#include <fstream>
#include <iostream>
class File { // class starts as private
public: // we make it public
File(const std::string& filename) {
file.open(filename);
if (!file.is_open()) {
throw std::runtime_error("Could not open file");
}
}
~File() {
file.close();
}
// Other methods to interact with the file...
private: // we make it private again
std::fstream file;
};
int main() {
try {
auto myFile = File("somefile.txt");
// Interact with myFile...
// Once we leave this scope, myFile is destructed and the file is automatically closed
} catch (const std::runtime_error& e) {
std::cout << "An error occurred: " << e.what() << std::endl;
}
return 0;
}