HTTP File Downloader

This program uses my socket class. Downloads a file specified by it’s http url.

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cstring>
#include "sock.h"
using namespace std;

void help() {
    cout <<
        "HTTP Downloader - by Jakash3" << endl <<
        "Usage: get FILE_URL OUTPUT_FILE" << endl;
    exit(1);
}

int main(int argc, char** argv) {
    if (argc!=3) help();
    char *host = argv[1], *url;
    if (strstr(argv[1], "http://") == argv[1]) host += 7;
    url = strchr(host, '/');
    if (!url || !host) { cout << "Not a valid HTTP URL!" << endl; return 1; }
    *url = 0;
    sock http;
    http.link(host, 80);
    *url = '/';
    http << "GET " << url << " HTTP/1.1\r\n";
    *url = 0;
    http << "Host: " << host << "\r\n\r\n";
    int i, len;
    while (http.readln()) {
        if (strstr(http.data, "HTTP/1.1 ") == http.data) {
            cout << (http.data + 9);
            if (strcmp(http.data + 9, "200 OK\r\n")) return 1;
        } else if (strstr(http.data, "Content-Length: ") == http.data) {
            *(strchr(http.data, '\r')) == 0;
            len = atoi(http.data + 16);
        } else if (!strcmp(http.data, "\r\n")) break;
    }
    ofstream of(argv[2]);
    if (!of.is_open()) { cout << "Failed to write to file!" << endl; return 1; }
    for (i = 0; i < len; i++) {
        http.read(1);
        of.put(*(http.data));
    }
    of.close();
    http.unlink();
    return 0;
}

Leave a comment