blob: 3a0ec5b66939f8b052f9d7a413562e1500bb861e [file] [log] [blame]
bigbiff7b4c7a62015-01-01 19:44:14 -05001#ifndef UTIL_LINUX_CAREFUULPUTC_H
2#define UTIL_LINUX_CAREFUULPUTC_H
3
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*/
9#include <stdio.h>
10#include <string.h>
11#include <ctype.h>
12
13static inline int fputc_careful(int c, FILE *fp, const char fail)
14{
15 int ret;
16
17 if (isprint(c) || c == '\a' || c == '\t' || c == '\r' || c == '\n')
18 ret = putc(c, fp);
19 else if (!isascii(c))
20 ret = fprintf(fp, "\\%3o", (unsigned char)c);
21 else {
22 ret = putc(fail, fp);
23 if (ret != EOF)
24 ret = putc(c ^ 0x40, fp);
25 }
26 return (ret < 0) ? EOF : 0;
27}
28
29static inline void fputs_quoted(const char *data, FILE *out)
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 || /* \ */
37 (unsigned char) *p == 0x60 || /* ` */
38 (unsigned char) *p == 0x24 || /* $ */
39 !isprint((unsigned char) *p) ||
40 iscntrl((unsigned char) *p)) {
41
42 fprintf(out, "\\x%02x", (unsigned char) *p);
43 } else
44 fputc(*p, out);
45 }
46 fputc('"', out);
47}
48
49static inline void fputs_nonblank(const char *data, FILE *out)
50{
51 const char *p;
52
53 for (p = data; p && *p; p++) {
54 if (isblank((unsigned char) *p) ||
55 (unsigned char) *p == 0x5c || /* \ */
56 !isprint((unsigned char) *p) ||
57 iscntrl((unsigned char) *p)) {
58
59 fprintf(out, "\\x%02x", (unsigned char) *p);
60
61 } else
62 fputc(*p, out);
63 }
64}
65
66
67#endif /* _CAREFUULPUTC_H */