Is there a standard C library function to escape C-strings?
For example, if I had the C string:
char example[] = \"first line\\nsecond line: \\\"inne
You just mentioned that you wanted to print the string.
char example[] = "first line\nsecond line: \"inner quotes\"";
size_t len = strlen(example);
size_t i;
static const char *simple = "\\\'\"";
static const char *complex = "\a\b\f\n\r\t\v";
static const char *complexMap = "abfnrtv";
for (i = 0; i < length; i++)
{
char *p;
if (strchr(simple, example[i]))
{
putchar('\\');
putchar(example[i]);
}
else if ((p = strchr(complex, example[i]))
{
size_t idx = p - complex;
putchar('\\');
putchar(complexMap[idx]);
}
else if (isprint(example[i]))
{
putchar(example[i]);
}
else
{
printf("\\%03o", example[i]);
}
}