]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - include/carefulputc.h
1 #ifndef UTIL_LINUX_CAREFULPUTC_H
2 #define UTIL_LINUX_CAREFULPUTC_H
13 * A puts() for use in write and wall (that sometimes are sgid tty).
14 * It avoids control and invalid characters.
15 * The locale of the recipient is nominally unknown,
16 * but it's a solid bet that it's compatible with the author's.
17 * Use soft_width=0 to disable wrapping.
19 static inline int fputs_careful(const char * s
, FILE *fp
, const char ctrl
, bool cr_lf
, int soft_width
)
23 for (size_t slen
= strlen(s
); *s
; ++s
, --slen
) {
25 col
+= (7 - (col
% 8)) - 1;
31 if ((soft_width
&& col
>= soft_width
) || *s
== '\n') {
33 fprintf(fp
, "%*s", soft_width
- col
, "");
36 ret
= fputs(cr_lf
? "\r\n" : "\n", fp
);
37 if (*s
== '\n' || ret
< 0)
41 if (isprint(*s
) || *s
== '\a' || *s
== '\t' || *s
== '\r') {
44 } else if (!c_isascii(*s
)) {
47 size_t clen
= mbtowc(&w
, s
, slen
);
49 case (size_t)-2: // incomplete
50 case (size_t)-1: // EILSEQ
51 mbtowc(NULL
, NULL
, 0);
53 col
+= ret
= fprintf(fp
, "\\%3hho", *s
);
58 ret
= fwrite(s
, 1, clen
, fp
);
66 col
+= ret
= fprintf(fp
, "\\%3hho", *s
);
69 ret
= fputs((char[]){ ctrl
, *s
^ 0x40, '\0' }, fp
);
80 static inline void fputs_quoted_case(const char *data
, FILE *out
, int dir
)
85 for (p
= data
; p
&& *p
; p
++) {
86 if ((unsigned char) *p
== 0x22 || /* " */
87 (unsigned char) *p
== 0x5c || /* \ */
88 (unsigned char) *p
== 0x60 || /* ` */
89 (unsigned char) *p
== 0x24 || /* $ */
90 !isprint((unsigned char) *p
) ||
91 iscntrl((unsigned char) *p
)) {
93 fprintf(out
, "\\x%02x", (unsigned char) *p
);
95 fputc(dir
== 1 ? toupper(*p
) :
96 dir
== -1 ? tolower(*p
) :
102 #define fputs_quoted(_d, _o) fputs_quoted_case(_d, _o, 0)
103 #define fputs_quoted_upper(_d, _o) fputs_quoted_case(_d, _o, 1)
104 #define fputs_quoted_lower(_d, _o) fputs_quoted_case(_d, _o, -1)
106 static inline void fputs_nonblank(const char *data
, FILE *out
)
110 for (p
= data
; p
&& *p
; p
++) {
111 if (isblank((unsigned char) *p
) ||
112 (unsigned char) *p
== 0x5c || /* \ */
113 !isprint((unsigned char) *p
) ||
114 iscntrl((unsigned char) *p
)) {
116 fprintf(out
, "\\x%02x", (unsigned char) *p
);
123 #endif /* _CAREFULPUTC_H */