All pastes #465275 Raw Edit

wget

public c v1 · immutable
#465275 ·published 2007-04-30 01:26 UTC
rendered paste body
int wget(char *url, FILE *file) {	int sockid = 0, idx = 0, len = 0, tmplen = 0;	char *uri, *host;	char *buf = (char*) malloc(MAX_BUFFER_LEN);	memset(buf, 0, sizeof(buf));	    wsaStart();		if (startsWith(url, "http://"))        url = &url[7];    idx = indexof(url, '/');    if (idx < 0)        return -1;    uri = &url[idx++];    host = (char*) malloc(idx);    memcpy(host, url, idx - 1);    host[idx-1] = 0;    uri[strlen(uri)-1] = 0;        // if the file is null, set it to the name of the file in the uri    if (file == NULL) {        idx = lastindexof(uri, '/') + 1;        char *name = &uri[idx];        file = fopen(name, "w");        if (file == NULL)            return -1;    }        // connect to the host and request the file    sockid = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    sockaddr_in addr = mkaddr(host, 80);	connect(sockid, (sockaddr*) &addr, sizeof(addr));	sockwrite(sockid, "GET %s HTTP/1.0\n", uri);	sockwrite(sockid, "Host: %s\n", host);	sockwrite(sockid, "\n");		// read the header until reached double newline	char prev = 0, read = 0;	while (read > -1) {        if (recv(sockid, &read, 1, 0) > 0) {            if (read == '\r') {                read = prev;                continue;            }            if (prev == '\n' && read == '\n')                break;            prev = read;        } else            return -2;    }	// read data until end of stream	while ((tmplen = recv(sockid, buf, sizeof(buf), 0)) > 0) {        int wrote = fwrite(buf, 1, tmplen, file);        if (wrote != tmplen)            return -3;        //fflush(file);        memset(buf, 0, sizeof(buf));        len += tmplen;    }		// cleanup	shutdown(sockid, SD_BOTH);	closesocket(sockid);	fclose(file);	free(buf);    return len;}