]>
Commit | Line | Data |
---|---|---|
78a3b0af KZ |
1 | #ifndef UTIL_LINUX_CAREFUULPUTC_H |
2 | #define UTIL_LINUX_CAREFUULPUTC_H | |
48d7b13a | 3 | |
459e95f3 BS |
4 | /* |
5 | * A putc() for use in write and wall (that sometimes are sgid tty). | |
6 | * It avoids control characters in our locale, and also ASCII control | |
7 | * characters. Note that the locale of the recipient is unknown. | |
8 | */ | |
66ee8158 | 9 | #include <stdio.h> |
78a3b0af KZ |
10 | #include <string.h> |
11 | #include <ctype.h> | |
66ee8158 | 12 | |
c6d2d74e SK |
13 | static inline int fputc_careful(int c, FILE *fp, const char fail) |
14 | { | |
66ee8158 KZ |
15 | int ret; |
16 | ||
c6d2d74e | 17 | if (isprint(c) || c == '\a' || c == '\t' || c == '\r' || c == '\n') |
66ee8158 | 18 | ret = putc(c, fp); |
c6d2d74e SK |
19 | else if (!isascii(c)) |
20 | ret = fprintf(fp, "\\%3o", (unsigned char)c); | |
66ee8158 | 21 | else { |
ada6c48f | 22 | ret = putc(fail, fp); |
66ee8158 | 23 | if (ret != EOF) |
c6d2d74e | 24 | ret = putc(c ^ 0x40, fp); |
66ee8158 KZ |
25 | } |
26 | return (ret < 0) ? EOF : 0; | |
27 | } | |
48d7b13a | 28 | |
6a768b55 | 29 | static inline void fputs_quoted_case(const char *data, FILE *out, int dir) |
78a3b0af KZ |
30 | { |
31 | const char *p; | |
32 | ||
33 | fputc('"', out); | |
34 | for (p = data; p && *p; p++) { | |
35 | if ((unsigned char) *p == 0x22 || /* " */ | |
36 | (unsigned char) *p == 0x5c || /* \ */ | |
cca51b9e KZ |
37 | (unsigned char) *p == 0x60 || /* ` */ |
38 | (unsigned char) *p == 0x24 || /* $ */ | |
78a3b0af KZ |
39 | !isprint((unsigned char) *p) || |
40 | iscntrl((unsigned char) *p)) { | |
41 | ||
42 | fprintf(out, "\\x%02x", (unsigned char) *p); | |
43 | } else | |
6a768b55 KZ |
44 | fputc(dir == 1 ? toupper(*p) : |
45 | dir == -1 ? tolower(*p) : | |
46 | *p, out); | |
78a3b0af KZ |
47 | } |
48 | fputc('"', out); | |
49 | } | |
50 | ||
6a768b55 KZ |
51 | #define fputs_quoted(_d, _o) fputs_quoted_case(_d, _o, 0) |
52 | #define fputs_quoted_upper(_d, _o) fputs_quoted_case(_d, _o, 1) | |
53 | #define fputs_quoted_lower(_d, _o) fputs_quoted_case(_d, _o, -1) | |
54 | ||
78a3b0af KZ |
55 | static inline void fputs_nonblank(const char *data, FILE *out) |
56 | { | |
57 | const char *p; | |
58 | ||
59 | for (p = data; p && *p; p++) { | |
60 | if (isblank((unsigned char) *p) || | |
61 | (unsigned char) *p == 0x5c || /* \ */ | |
62 | !isprint((unsigned char) *p) || | |
63 | iscntrl((unsigned char) *p)) { | |
64 | ||
65 | fprintf(out, "\\x%02x", (unsigned char) *p); | |
66 | ||
67 | } else | |
68 | fputc(*p, out); | |
69 | } | |
70 | } | |
71 | ||
72 | ||
48d7b13a | 73 | #endif /* _CAREFUULPUTC_H */ |