-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathProcReader.cpp
121 lines (94 loc) · 1.92 KB
/
ProcReader.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
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
119
120
121
/*
* ProcReader.cpp
*
* Created on: 15/lug/2013
* Author: Stefano Ceccherini
*/
#include "ProcReader.h"
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <string>
#include <stdexcept>
#include <unistd.h>
#include <sys/ioctl.h>
ProcReader::ProcReader(const char* fullPath)
{
if (ProcReader::open(fullPath, "r") == NULL) {
std::string errorString;
errorString.append("File not found: ");
errorString.append(fullPath);
throw std::runtime_error(errorString);
}
}
ProcReader::~ProcReader()
{
close();
}
std::string
ProcReader::ReadLine()
{
std::string line;
std::istream buf(this);
std::getline(buf, line);
return line;
}
ProcReader*
ProcReader::open(const char* fileName, const char* mode)
{
fFD = ::open(fileName, O_RDONLY);
if (fFD < 0)
return NULL;
fBuffer = new char[512];
if (fBuffer == NULL)
return NULL;
setg(fBuffer, fBuffer, fBuffer);
return this;
}
void
ProcReader::close()
{
if (fFD >= 0) {
::close(fFD);
fFD = -1;
}
delete[] fBuffer;
fBuffer = NULL;
}
std::streamsize
ProcReader::xsgetn(char_type* ptr, std::streamsize num)
{
std::streamsize howMany = showmanyc();
if (num < howMany) {
memcpy(ptr, gptr(), num * sizeof(char_type));
gbump(num);
return num;
}
memcpy(ptr, gptr(), howMany * sizeof(char_type));
gbump(howMany);
if (traits_type::eof() == underflow())
return howMany;
return howMany + xsgetn(ptr + howMany, num - howMany);
}
ProcReader::traits_type::int_type
ProcReader::underflow()
{
if (gptr() == 0)
return traits_type::eof();
if (gptr() < egptr())
return traits_type::to_int_type(*gptr());
size_t len = ::read(fFD, eback(), sizeof(char_type) * 512);
setg(eback(), eback(), eback() + sizeof(char_type) * len);
if (len == 0)
return traits_type::eof();
return traits_type::to_int_type(*gptr());
}
std::streamsize
ProcReader::showmanyc()
{
if (gptr() == 0)
return 0;
if (gptr() < egptr())
return egptr() - gptr();
return 0;
}