简体   繁体   English

如何在C中的char *字符串中转义特殊字符

[英]How to escape special characters in a char* string in C

I'm getting a string from fgets function. 我从fgets函数得到一个字符串。 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. 我想将该字符串清除为一个新字符串,以便第二个字符串都转义了所有特殊的和潜在的危险字符,类似于在PHP中使用addslashes()或mysql_real_escape_string()可以执行的操作。 As defined in the PHP Manual: 如PHP手册中所定义:

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. mysql_real_escape_string()调用MySQL的库函数mysql_real_escape_string,该函数将反斜杠添加到以下字符之前:\\ x00,\\ n,\\ r,\\,','和\\ 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. 我既无意将此数据发送到mysql查询,也无意与任何SQL Server建立当前连接,只是希望在运行于Linux机器上的简单CLI C程序中将其清除。 This is gonna be used in a simple Static Analysis with Splint . 这将用于带有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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM