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。