-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy patherror_code.cpp
More file actions
51 lines (43 loc) · 1.11 KB
/
error_code.cpp
File metadata and controls
51 lines (43 loc) · 1.11 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
#include <cstdio>
#include <fstream>
#include <iostream>
#include <system_error>
void open_file(const std::string &filename, std::error_code &ec) {
std::ifstream file(filename);
if (!file) {
ec = std::make_error_code(std::errc::no_such_file_or_directory);
return;
}
// Process file...
ec.clear(); // No error
}
void delete_file(const std::string &filename, std::error_code &ec) {
if (std::remove(filename.c_str()) != 0) {
ec = std::error_code(errno, std::system_category());
} else {
ec.clear(); // No error
}
}
int main() {
{
std::error_code ec;
open_file("non_existent_file.txt", ec);
if (ec) {
std::cout << "Error opening file: " << ec.message()
<< " (Error code: " << ec.value() << ")\n";
} else {
std::cout << "File opened successfully.\n";
}
}
{
std::error_code ec;
delete_file("non_existent_file.txt", ec);
if (ec) {
std::cout << "Error deleting file: " << ec.message()
<< " (Error code: " << ec.value() << ")\n";
} else {
std::cout << "File deleted successfully.\n";
}
}
return 0;
}