This repository has been archived by the owner on Dec 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemoryinfo.cpp
123 lines (115 loc) · 2.42 KB
/
memoryinfo.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
122
123
#include "memoryinfo.h"
using namespace std;
//去除字符串中的制表符
std::string memory_trim(std::string &s)
{
if (!s.empty())
{
// cout<<"flag "<<s.find_last_not_of("\t")<<endl;
s.erase(0,s.find_first_not_of(" "));
s.erase(s.find_last_not_of("\t") + 1);
}
return s;
}
// ---- get memory info ---- //
std::vector<Memory> getMemoryInfo() {
std::vector<Memory> memories;
ifstream file;
file.open("/proc/meminfo");
if (!file.good())
printf("failed to open meminfo\n");
// read file line by line
std::string temp;
std::string name;
std::string value;
// 用于将字符串转为整型
int temp1=0;
Memory memory;
memory.id="0";
while (getline(file,temp))
{
int pos=temp.find_first_of(":");
// cout<<temp1<<endl;
// cout<<"flag"<<pos<<endl;
name=temp.substr(0,pos);
value=temp.substr(pos+1);
// cout<<"line"<<i++<<endl;
// cout<<value<<endl;
// name=memory_trim(name);
value=memory_trim(value);
// cout<<name<<"end"<<endl;
if(name == "MemTotal")
{
stringstream geek;
geek<<value;
geek>>temp1;
temp1=temp1/1024;
stringstream geek1;
geek1<<temp1;
geek1>>memory.total;
memory.total=memory.total+" MB";
}
else if(name == "MemFree")
{
stringstream geek;
geek<<value;
geek>>temp1;
// cout<<temp1<<endl;
temp1=temp1/1024;
stringstream geek1;
geek1<<temp1;
geek1>>memory.free;
memory.free=memory.free+" MB";
}
else if(name == "Active")
{
stringstream geek;
geek<<value;
geek>>temp1;
// cout<<temp1<<endl;
temp1=temp1/1024;
stringstream geek1;
int a=0;
geek1<<memory.total;
geek1>>a;
// cout<<"a"<<a<<" b"<<temp1<<endl;
stringstream geek2;
geek2<<(a-temp1);
geek2>>memory.used;
memory.used=memory.used+" MB";
}
else if(name == "Inactive")
{
stringstream geek;
geek<<value;
geek>>temp1;
temp1=temp1/1024;
stringstream geek1;
geek1<<temp1;
geek1>>memory.shared;
memory.shared=memory.shared+" MB";
}
else if(name == "Cached")
{
stringstream geek;
geek<<value;
geek>>temp1;
temp1=temp1/1024;
stringstream geek1;
geek1<<temp1;
geek1>>memory.cache;
memory.cache=memory.cache+" MB";
}
}
memories.push_back(memory);
file.close();
return memories;
}
/* int main()
{
printf("=== memory infomation ===\n");
Memory memory;
memory=getMemoryInfo();
memory.tostring();
return 0;
} */