【问题标题】:strstr doesn't work with the delimiter "\r\n\r\n"strstr 不适用于分隔符“\r\n\r\n”
【发布时间】:2021-05-16 16:02:25
【问题描述】:

我在子字符串中得到了分隔符“\r\n\r\n”,而strstr返回null

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int ac, char **av) {
  char *ptr;

  ptr = strstr(av[1], "\r\n\r\n");
  printf("ptr = %s\n", ptr);
  return 0;
}

我用这个启动代码:

./a.out "POST /cgi-bin/process.cgi HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nContent-Type: text/xml; charset=utf-8\nContent-Length: length\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\r\n\r\n<?xml version='1.0' encoding='utf-8'?>"

而ptr等于(null),为什么?

【问题讨论】:

  • 删除了我的评论,伙计们是对的:需要转义反斜杠。
  • strstr() 在没有找到搜索到的字符串时返回NULL。您可以在strstr() 的手册页中查看。

标签: c newline strstr


【解决方案1】:

您传递给代码的字符串包含八个字符序列\、r、\、n、\、r、\、n。

字符串文字"\r\n\r\n" 产生四个字符序列␍、␊、␍、␊。


要生成与参数匹配的字符串,请使用以下字符串文字:

"\\r\\n\\r\\n"

但我认为您更有可能想要提供正确的 HTTP 请求。

根据您使用的echo,echo 或echo -e 可能会生成所需的字符串(加上尾随换行符):

$ echo -e 'a\r\nb\r\n' | od -c
0000000   a  \r  \n   b  \r  \n  \n
0000007

printf 可以可靠地生成您想要的字符串,但您必须通过复制 % 符号来转义它们。

$ printf 'a\r\n%%\r\n' | od -c
0000000   a  \r  \n   %  \r  \n
0000006

示例用法:

./a.out "$( printf 'POST ...\r\n\r\n...' )"

【讨论】:

    【解决方案2】:

    在您的情况下,您必须使用strstr(av[1], "\\r\\n\\r\\n")

    【讨论】:

    • 这不是本意。问题是如何通过命令行提供一个包含 cr 和 lf 的字符串。
    【解决方案3】:

    你也可以使用 bash $'string' 引用:

    $ ./a.out $'POST /cgi-bin/process.cgi HTTP/1.1\nUser-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\nHost: www.tutorialspoint.com\nContent-Type: text/xml; charset=utf-8\nContent-Length: length\nAccept-Language: en-us\nAccept-Encoding: gzip, deflate\nConnection: Keep-Alive\r\n\r\n<?xml version=\'1.0\' encoding=\'utf-8\'?>'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-30
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      相关资源
      最近更新 更多