]>
git.ipfire.org Git - thirdparty/util-linux.git/blob - include/carefulputc.h
1 #ifndef UTIL_LINUX_CAREFULPUTC_H
2 #define UTIL_LINUX_CAREFULPUTC_H
16 * A puts() for use in write and wall (that sometimes are sgid tty).
17 * It avoids control and invalid characters.
18 * The locale of the recipient is nominally unknown,
19 * but it's a solid bet that it's compatible with the author's.
20 * Use soft_width=0 to disable wrapping.
22 static inline int fputs_careful(const char * s
, FILE *fp
, const char ctrl
, bool cr_lf
, int soft_width
)
26 for (size_t slen
= strlen(s
); *s
; ++s
, --slen
) {
28 col
+= (7 - (col
% 8)) - 1;
34 if ((soft_width
&& col
>= soft_width
) || *s
== '\n') {
36 fprintf(fp
, "%*s", soft_width
- col
, "");
39 ret
= fputs(cr_lf
? "\r\n" : "\n", fp
);
40 if (*s
== '\n' || ret
< 0)
44 if (isprint(*s
) || *s
== '\a' || *s
== '\t' || *s
== '\r') {
47 } else if (!c_isascii(*s
)) {
50 size_t clen
= mbtowc(&w
, s
, slen
);
52 case (size_t)-2: // incomplete
53 case (size_t)-1: // EILSEQ
54 mbtowc(NULL
, NULL
, 0);
56 col
+= ret
= fprintf(fp
, "\\%3hho", *s
);
61 ret
= fwrite(s
, 1, clen
, fp
);
69 col
+= ret
= fprintf(fp
, "\\%3hho", *s
);
72 ret
= fputs((char[]){ ctrl
, *s
^ 0x40, '\0' }, fp
);
83 static inline void fputs_quoted_case(const char *data
, FILE *out
, int dir
)
88 for (p
= data
; p
&& *p
; p
++) {
89 if ((unsigned char) *p
== 0x22 || /* " */
90 (unsigned char) *p
== 0x5c || /* \ */
91 (unsigned char) *p
== 0x60 || /* ` */
92 (unsigned char) *p
== 0x24 || /* $ */
93 !isprint((unsigned char) *p
) ||
94 iscntrl((unsigned char) *p
)) {
96 fprintf(out
, "\\x%02x", (unsigned char) *p
);
98 fputc(dir
== 1 ? toupper(*p
) :
99 dir
== -1 ? tolower(*p
) :
105 #define fputs_quoted(_d, _o) fputs_quoted_case(_d, _o, 0)
106 #define fputs_quoted_upper(_d, _o) fputs_quoted_case(_d, _o, 1)
107 #define fputs_quoted_lower(_d, _o) fputs_quoted_case(_d, _o, -1)
109 static inline void fputs_nonblank(const char *data
, FILE *out
)
113 for (p
= data
; p
&& *p
; p
++) {
114 if (isblank((unsigned char) *p
) ||
115 (unsigned char) *p
== 0x5c || /* \ */
116 !isprint((unsigned char) *p
) ||
117 iscntrl((unsigned char) *p
)) {
119 fprintf(out
, "\\x%02x", (unsigned char) *p
);
126 #endif /* _CAREFULPUTC_H */