我试图找到最后一次出现的 \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?
它清楚地将 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/