C 尝试在 header 中查找\r\n\r\n

标签 c windows

我试图找到最后一次出现的 \r\n\r\n 并删除它之前的所有内容(包括它)。我正在创建一个套接字并下载一个文件,然后该文件将被保存。 HTTP header 保存在文件中(并且根据十六进制编辑器 \r\n\r\n 确实存在)。但我似乎无法使用 strstr 找到它,根据 MSDN recv 返回 char 所以它应该能够找到它?

    while ((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0)
    {
char *p = strstr(buf, "\r\n\r\n");
printf("%s", p);
exit(1);
        if (fwrite(buf, 1, tmpres, fp) != tmpres) {
            printf("Error writing buffer");
            exit(1);
        }
    }

但是 strstr 返回 null?

hex codes

它清楚地将 0D0A0D0A 写入文件,因此我不确定发生了什么。

最佳答案

啊,文本文件和标准 I/O 的奇迹。

当您以文本模式打开文件时, native 行结尾会发生更改,以便程序看到的只是 \n 作为行结尾,即使磁盘上的内容不同。

要查看 \r\n 行结尾,您必须以二进制模式打开文件。

ISO/IEC 9899:2011 §7.21.2 Streams

¶2 A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a oneto- one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

关于C 尝试在 header 中查找\r\n\r\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971164/

相关文章:

c - 使用位掩码将有符号整数转换为二进制补码

c++ - 如何控制 DLL 的搜索顺序以避免劫持?

windows - windows平台上如何获取进程发送或接收的数据量?

c++ - 如何为 native Windows(而不是 X Windows)编译 gtk+ 应用程序?

c - C 中 ascii 字符串的奇怪行为

c - 通过计算汇编指令来测量 CPU 速度

c++ - WriteFileGather - 写入大文件(大于 4 GB)的方法是什么?

c++ - 错误 124 - SHFileOperation 的系统调用级别不正确

c - 为什么 C 没有旋转左/右运算符?

c - 为什么 malloc+memset 比 calloc 慢?