Reputation: 13735
The following function implements a way to print a character array in a quoted form.
https://github.com/antirez/sds
...
s2 = sdscatrepr(s2,s1,sdslen(s1));
printf("%s\n", s2);
output> "a\x01\x02\n"
But it depends on an external library. Is there a native C function for the same purpose?
Upvotes: 1
Views: 73
Reputation: 144969
Is there a native C function for the same purpose?
No, there is not.
The code in reference is not as simple as it should be. It implements a more general task. To print a character in readable form use this:
int print_char(unsigned char c) {
switch (c) {
case '\\': return printf("\\\\");
case '"': return printf("\\\"");
case '\n': return printf("\\n");
case '\r': return printf("\\r");
case '\t': return printf("\\t");
case '\f': return printf("\\f");
case '\a': return printf("\\a");
case '\b': return printf("\\b");
default:
if (isprint(c))
return printf("%c", c);
else
return printf("\\x%02x", c);
}
}
int print_string(const char *s, size_t len) {
int res = printf("\"");
for (size_t i = 0; i < len; i++) {
res += print_char(s[i]);
}
return res + printf("\"");
}
Upvotes: 3