wangzhengquan
2020-06-19 1b26f1dd275e7ff947fcf2ecdbbad8f6bc1e0b49
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
#include "usg_common.h"
#include <errno.h>        /* for definition of errno */
 
#define MAXLINE 4096      /* max line length */
/**************************
 * Error-handling functions
 **************************/
 
static void    err_doit(int, const char *, va_list);
 
 
/*void unix_error(const char *fmt, ...) */
/*{*/
    /*va_list        ap;*/
 
    /*va_start(ap, fmt);*/
    /*err_doit(errno, fmt, ap);*/
    /*va_end(ap);*/
/*}*/
 
void posix_error(int code, const char *fmt, ...) /* Posix-style error */
{
    va_list        ap;
 
    va_start(ap, fmt);
    err_doit(code, fmt, ap);
    va_end(ap);
}
 
/*
 * Fatal error unrelated to a system call.
 * Error code passed as explict parameter.
 * Print a message and terminate.
 */
void err_exit(int error, const char *fmt, ...)
{
    va_list        ap;
 
    va_start(ap, fmt);
    err_doit(error, fmt, ap);
    va_end(ap);
    //abort();        /* dump core and terminate */
    exit(1);
}
 
 
 
/*
 * Nonfatal error unrelated to a system call.
 * Print a message and return.
 */
void err_msg(int error, const char *fmt, ...)
{
    va_list        ap;
 
    va_start(ap, fmt);
    err_doit(error, fmt, ap);
    va_end(ap);
}
 
 
/*
 * Print a message and return to caller.
 * Caller specifies "errnoflag".
 */
static void err_doit(int error, const char *fmt, va_list ap)
{
    char    buf[MAXLINE];
 
    vsnprintf(buf, MAXLINE-1, fmt, ap);
    if (error != 0) {
        snprintf(buf+strlen(buf), MAXLINE-strlen(buf)-1, ": %s", strerror(error));
    }
    strcat(buf, "\n");
    fflush(stdout);        /* in case stdout and stderr are the same */
    fputs(buf, stderr);
    fflush(NULL);        /* flushes all stdio output streams */
}
 
char *ltrim(char *str, const char *seps)
{
    size_t totrim;
    if (seps == NULL) {
        seps = "\t\n\v\f\r ";
    }
    totrim = strspn(str, seps);
    if (totrim > 0) {
        size_t len = strlen(str);
        if (totrim == len) {
            str[0] = '\0';
        }
        else {
            memmove(str, str + totrim, len + 1 - totrim);
        }
    }
    return str;
}
 
char *rtrim(char *str, const char *seps)
{
    int i;
    if (seps == NULL) {
        seps = "\t\n\v\f\r ";
    }
    i = strlen(str) - 1;
    while (i >= 0 && strchr(seps, str[i]) != NULL) {
        str[i] = '\0';
        i--;
    }
    return str;
}
 
char *trim(char *str, const char *seps)
{
    return ltrim(rtrim(str, seps), seps);
}