检查EOF时,套接字/文件流上的C fgetc()进入无限循环

时间:2012-11-06 11:33:05

标签: c loops eof infinite fgetc

int main(int argc, char *argv[]) {

    int conn_s = socket(AF_INET, SOCK_STREAM, 0);
    struct addrinfo hints;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;

    struct addrinfo *addr = (struct addrinfo *) calloc(1, sizeof(struct addrinfo));

    getaddrinfo("google.com", "80", &hints, &addr);

    connect(conn_s, addr->ai_addr, sizeof(struct sockaddr_in));

    char *http_request = "GET / HTTP/1.1\n\n";

    send(conn_s, http_request, strlen(http_request), 0);
    FILE *sockfile = (FILE *) fdopen(conn_s, "r");
    FILE *fp = fopen("/Users/leekaiwei/Desktop/results.html", "w+");
    int ch;

    while ((ch = fgetc(sockfile)) != EOF) {
        fprintf(fp, "%c", ch);
    }

    close(conn_s);
    fclose(fp);
    fclose(sockfile);
    free(addr);
    return 0;
}

while循环永远不会结束。为什么是这样?我用本地文件完成了它,它工作正常。它也适用于for循环,只是fgetc()永远不会返回EOF。

1 个答案:

答案 0 :(得分:2)

HTTP/1.1默认为connection: keepalive,所以像simonc所说的那样,服务器实际上正在等待您发出下一个请求,并将等到服务器相关的超时。 使用HTTP/1.0获取EOF

FWIW:完成需要245秒。