Created
June 8, 2009 19:43
-
-
Save kulp/126016 to your computer and use it in GitHub Desktop.
Copies a string, replacing unprintable and some punctuation characters with their C-escaped versions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copies a string from 'in' to 'out', replacing unprintable and some | |
* punctuation characters with their escaped versions. | |
* | |
* To be safe, the output buffer should be allocated with (4 * ilen) characters | |
* of space, for the worst case scenario, where all characters are unprintable. | |
* | |
* @param ilen the length of the input string | |
* @param in the input string | |
* @param olen the length of the output buffer | |
* @param out the output buffer | |
* | |
* @return the number of characters copied | |
*/ | |
int _c_encode_string(int ilen, char in[ilen], int olen, char out[olen]) | |
{ | |
int pos = 0; | |
for (int i = 0; i < ilen && pos < olen; i++) { | |
char c = in[i]; | |
if (isprint(c) && !ispunct(c)) { | |
out[pos++] = c; | |
} else { | |
switch (c) { | |
case '\a': out[pos++] = '\\'; out[pos++] = 'a'; break; | |
case '\b': out[pos++] = '\\'; out[pos++] = 'b'; break; | |
case '\f': out[pos++] = '\\'; out[pos++] = 'f'; break; | |
case '\n': out[pos++] = '\\'; out[pos++] = 'n'; break; | |
case '\r': out[pos++] = '\\'; out[pos++] = 'r'; break; | |
case '\t': out[pos++] = '\\'; out[pos++] = 't'; break; | |
case '\v': out[pos++] = '\\'; out[pos++] = 'v'; break; | |
case '\"': out[pos++] = '\\'; out[pos++] = '\"'; break; | |
default: | |
if (ispunct(c)) out[pos++] = c; | |
else pos += sprintf(&out[pos], "\\%03o", c); | |
break; | |
} | |
} | |
} | |
out[pos] = 0; | |
return pos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment