I am requesting and receiving from a web server. While I can output what I receive into stdout, I can't seem to put it into a file.
Thanks.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
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.txt", "w");
int ch;
while ((ch = fgetc(sockfile)) != EOF) {
printf("%c", ch);
fputc(ch, fp);
}
close(conn_s);
free(addr);
fclose(fp);
fclose(sockfile);
return 0;
}
Thanks.







