我正在尝试编写一个通过套接字读取一行文本的函数(这是我为作业的 HTTP 服务器编写的代码的一部分)。
当我使用fputc
. 但是,当我尝试将字符复制到缓冲区,然后使用fprintf
将整个缓冲区打印到文件时,我似乎没有得到任何输出。
这是代码:
int read_line(int fd, char *buffer, int size) {
char *broken_buffer = (char*) malloc(sizeof(char) * 8096);
char next = '\0';
char err;
int i = 0;
FILE *f = fopen("read_line2.txt", "w");
while (i < size - 1 && next != '\n') {
err = read(fd, &next, 1);
if (err > 0) {
if (next == '\r') {
err = recv(fd, &next, 1, MSG_PEEK);
if (err > 0 && next == '\n') {
read(fd, &next, 1);
} else {
next = '\n';
}
}
fputc(next, f); // Works
broken_buffer[i] = next;
buffer[i] = next;
i++;
} else {
next = '\n';
}
}
broken_buffer[i] = '\0';
buffer[i] = '\0';
FILE *out = fopen("read_line.txt", "w");
fprintf(out, "%s\n", broken_buffer); // Does not work
fclose(out);
fclose(f);
return i;
}
编辑:我试过使用这个替代功能:
int read_socket(int fd, char *buffer, int size) {
int bytes_recvd = 0;
int retries = 0;
int total_recvd = 0;
while (retries < MAX_RETRIES && size > 0 && strstr(buffer, ">") == NULL) {
bytes_recvd = read(fd, buffer, size);
if (bytes_recvd > 0) {
buffer += bytes_recvd;
size -= bytes_recvd;
total_recvd += bytes_recvd;
} else {
retries++;
}
}
if (bytes_recvd >= 0) {
// Last read was not an error, return how many bytes were recvd
return total_recvd;
}
// Last read was an error, return error code
return -1;
}
我用 fprintf 打印这个没有问题。
EDIT2:我发现i
循环后不知何故为0,因此第一个字符被'\ 0'覆盖。但是,当我输入调试代码以打印循环中 i 的值时,我发现它被增加到 22(23 是循环中断的最终值)。这怎么可能?结果字符串是:
GET /blah.txt HTTP/1.1