#include <string.h>
/* int c_quote(const char* src, char* dest, int maxlen)
*
* Quotes the string given so that it will be parseable by a c compiler.
* Return the number of chars copied to the resulting string (including any nulls)
*
* if dest is NULL, no copying is performed, but the number of chars required to
* copy will be returned.
*
* maxlen characters are copied. If maxlen is negative,
* strlen is used to find the length of the source string, and the whole string
* including the NULL-terminator is copied.
*
* Note that this function will not null-terminate the string in dest.
* If the string in src is not null-terminated, or maxlen is specified to not
* include the whole src, remember to null-terminate dest afterwards.
*
*/
int c_quote(const char* src, char* dest, int maxlen) {
int count = 0;
if(maxlen < 0) {
maxlen = strlen(src)+1; /* add 1 for NULL-terminator */
}
while(src && maxlen > 0) {
switch(*src) {
/* these normal, printable chars just need a slash appended */
case '\\':
case '\"':
case '\'':
if(dest) {
*dest++ = '\\';
*dest++ = *src;
}
count += 2;
break;
/* newlines/tabs and unprintable characters need a special code.
* Use the macro CASE_CHAR defined below.
* The first arg for the macro is the char to compare to,
* the 2nd arg is the char to put in the result string, after the '\' */
#define CASE_CHAR(c, d) case c:\
if(dest) {\
*dest++ = '\\'; *dest++ = (d);\
}\
count += 2;\
break;
/* -------------- */
CASE_CHAR('\n', 'n');
CASE_CHAR('\t', 't');
CASE_CHAR('\b', 'b');
/* ------------- */
#undef CASE_CHAR
/* by default, just copy the char over */
default:
if(dest) {
*dest++ = *src;
}
count++;
}
++src;
--maxlen;
}
return count;
}