I'm getting a string from fgets function. I want to clean that string into a new string so that the second has all special and potentially dangerous characters scaped, something similar to what you could do with addslashes() or mysql_real_escape_string() in PHP. As defined in the PHP Manual:
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \\x00, \\n, \\r, \\, ', " and \\x1a.
I do not intent to send this data to a mysql query nor do I have a current connection to any SQL server, just want it cleaned in a simple CLI C program running in a linux machine. This is gonna be used in a simple Static Analysis with Splint . I have looked into several other questions here and haven't got it.
void clean_string(char * origin, char * destiny)
{
//copies the origin to destiny scaping characters
}
You can work with the string directly. Loop through each position of the character array and if you have a special character then just replace it with something else.
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "Hello\tworld\n!";
int i, len;
len = strlen(str);
printf("%s\n", str);
for (i = 0; i < len; ++i) {
switch (str[i]) {
case '\n':
str[i] = '$';
break;
case '\t':
str[i] = '$';
break;
}
}
printf("%s\n", str);
return 0;
}
It is still unclear why you think the string has "dangerous" chars, but if you want to escape some of them:
const char *str = "my dangerous";
const char *ooh = "aeoui\\";
char buf[BIG_ENOUGH];
size_t bp = 0;
for (size_t sp = 0; str[sp]; sp++) {
if (strchr(ooh, str[sp])) buf[bp++] = '\\';
buf[bp++] = str[sp];
}
buf[bp] = 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.