qilin said:
I am trying to save a big text string into MySQL, but I guess i need
escape the string firstly, anybody knows any escape function in c for
that? or any other suggests ?
Here's some code from my comma-separated valuses to C struct converter.
You'll have to change it to make the FILE * into a pointer to a buffer -
remember to make it at least twice as big as the string plus one in case
passed a string full of escapes.
/*
write a string as a C string to stream
Params: str - the string
fp - output file
Notes:handles escapes
*/
int dumpstring(const char *str, FILE *fp)
{
char buff[64];
if(!str)
{
fprintf(fp, "0");
return 0;
}
fputc('\"', fp);
while(*str)
{
if(escaped(*str))
{
escape(buff, *str);
fprintf(fp, "%s", buff);
}
fputc(*str, fp);
str++;
}
fputc('\"', fp);
return 0;
}
/*
is a character escaped?
Params: ch - character to test
Returns: 1 if escaped, 0 if normal
*/
int escaped(int ch)
{
return strchr("\\\a\b\n\r\t\'\"\f\v", ch) ? 1 : 0;
}
/*
get the escape sequence for a character
Params: out - output buffer (currently max 2 + nul but allow for more)
ch - the character to escape
*/
void escape(char *out, int ch)
{
switch(ch)
{
case '\n':
strcpy(out, "\\n"); break;
case '\t':
strcpy(out, "\\t"); break;
case '\v':
strcpy(out, "\\v"); break;
case '\b':
strcpy(out, "\\b"); break;
case '\r':
strcpy(out, "\\r"); break;
case '\f':
strcpy(out, "\\f"); break;
case '\a':
strcpy(out, "\\a"); break;
case '\\':
strcpy(out, "\\\\"); break;
case '\'':
strcpy(out, "\\\'"); break;
case '\"':
strcpy(out, "\\\""); break;
default:
out[0] = (char) ch; break;
out[1] = 0;
}
}