-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUtil.cpp
76 lines (68 loc) · 1.93 KB
/
Util.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
#include "Util.h"
static const char *levelname[] = {"INFO","WARN", "ERROR", "FATAL"};
FILE *Util::logfd = stdout;
int Util::setfd(const string &filename)
{
if(filename == "") return 1;
if((logfd = fopen(filename.c_str(), "a+")) == NULL) {
return 0;
}
return 1;
}
void Util::write(int levels, const char *file, const int line, const char *func, const char *format, ...)
{
char buf[LOGBUFSIZE];
va_list ap;
va_start(ap, format);
vsnprintf(buf, LOGBUFSIZE, format, ap);
va_end(ap);
time_t now;
struct tm *tm;
time(&now);
tm = localtime(&now);
char str[LINEBUFSIZE];
#ifdef _DARWIN
snprintf(str, LINEBUFSIZE, "%s %02d:%02d:%02d [%lu] %s", levelname[levels], tm->tm_hour,tm->tm_min,tm->tm_sec, pthread_self()->__sig, buf);
#else
snprintf(str, LINEBUFSIZE, "%s %02d:%02d:%02d [%lu] %s", levelname[levels], tm->tm_hour,tm->tm_min,tm->tm_sec, pthread_self(), buf);
#endif
fprintf(logfd, "%s\n", str);
fflush(logfd);
}
BYTE Util::fromHex(const BYTE &x)
{
return isdigit(x) ? x-'0' : x-'A'+10;
}
string Util::URLDecode(const string &sIn, string &sOut) {
for( size_t ix = 0; ix < sIn.size(); ix++ )
{
BYTE ch = 0;
if(sIn[ix]=='%')
{
ch = (fromHex(sIn[ix+1])<<4);
ch |= fromHex(sIn[ix+2]);
ix += 2;
}
else if(sIn[ix] == '+')
{
ch = ' ';
}
else
{
ch = sIn[ix];
}
sOut += (char)ch;
}
return sOut;
}
void Util::ReplaceSpace(string &str) {
string special[4] = {"\t"," ","\r","\n"};
string rep = "";
for(int i=0; i<4; i++) {
size_t pos=0;
while((pos = str.find_first_of(special[i], pos))!=string::npos) {
str.replace(pos, 1, rep);
pos += 1;
}
}
}