Repository navigation
Expand file tree
/
Copy pathio.cpp
More file actions
118 lines (84 loc) · 2.5 KB
/
Copy pathio.cpp
File metadata and controls
118 lines (84 loc) · 2.5 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "io.h"
#include <cstring>
#include <stdexcept>
#include <cerrno>
namespace custom
{
IStream in;
OStream out;
ErrStream err;
// ===========IStream===========
IStream& IStream::get(char& c)
{
is_eof_ = false;
ssize_t num_of_bytes {::read(fd_, &c, 1)};
if (num_of_bytes == 0)
is_eof_ = true;
else if (num_of_bytes == -1)
throw std::runtime_error("System input call error: " +
std::string(std::strerror(errno)));
return *this;
}
IStream& IStream::getline(std::string& str, char delim)
{
is_eof_ = false;
str.erase();
char buf[256] {0};
ssize_t num_of_bytes {sizeof(buf)};
bool is_delim {false};
size_t chars_to_append;
while(!(num_of_bytes < sizeof(buf) || is_delim))
{
num_of_bytes = ::read(fd_, buf, sizeof(buf));
if (num_of_bytes <= 0)
break;
is_delim = buf[num_of_bytes - 1] == endl;
chars_to_append = is_delim ? num_of_bytes - 1
: num_of_bytes;
str.append(buf, chars_to_append);
}
if (num_of_bytes == 0)
is_eof_ = true;
else if (num_of_bytes == -1)
throw std::runtime_error("System input call error: " +
std::string(std::strerror(errno)));
return *this;
}
IStream& IStream::read_all(std::string& str)
{
is_eof_ = false;
str.erase();
char buf[256] {0};
ssize_t num_of_bytes {sizeof(buf)};
while(num_of_bytes == sizeof(buf))
{
num_of_bytes = ::read(fd_, buf, sizeof(buf));
if (num_of_bytes <= 0)
break;
str.append(buf, num_of_bytes);
}
if (num_of_bytes == 0)
is_eof_ = true;
else if (num_of_bytes == -1)
throw std::runtime_error("System input call error: " +
std::string(std::strerror(errno)));
return *this;
}
// ===========OStream===========
OStream& OStream::put(char c)
{
ssize_t num_of_bytes {::write(fd_, &c, 1)};
if (num_of_bytes == -1)
throw std::runtime_error("System output call error: " +
std::string(std::strerror(errno)));
return *this;
}
OStream& OStream::write(const std::string& str)
{
ssize_t num_of_bytes {::write(fd_, str.data(), str.size())};
if (num_of_bytes == -1)
throw std::runtime_error("System output call error: " +
std::string(std::strerror(errno)));
return *this;
}
} // namespace custom