vish213
vish213

Reputation: 786

How to fetch a page's HTML code from www using C?

I just want to fetch a webpage(its HTML code,if its like www.example.com/example.html) into a text file using C. Is it possible using any library study or anything? I am really getting lost into "maybe i should learn" PHP or python or something and then use command line invocation of these scripts using system() or exec(). Whats the best way to do so?

My Exact current need is to fetch http://livechat.rediff.com/sports/score/score.txt, which by chance happened to be a .txt file.

Upvotes: 3

Views: 1072

Answers (2)

Robert Gamble
Robert Gamble

Reputation: 109022

As Toby already mentioned, libcurl is probably your best bet. Here is an actual program demonstrating how retrieve a webpage using the libcurl-easy interface:

#include <stdio.h>
#include <curl/curl.h>

int main(int argc, char *argv[]) {
    CURL *curl;
    CURLcode curl_result;
    const char *site;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s site\n", argv[0]);
        return 1;
    }   

    site = argv[1];

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, site);
        curl_result = curl_easy_perform(curl);

        if(curl_result != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(curl_result));
        }   

        curl_easy_cleanup(curl);
    }   
    else {
        fprintf(stderr, "Failed to initialize curl\n");
        return 1;
    }   

    return 0;
}

The program takes one argument, the name of the site to retrieve. When compiled with gcc curltest.c -lcurl -o curltest and run as curltest http://livechat.rediff.com/sports/score/score.txt, outputs the following:

l1=England vs South Africa
l2=England
interval=1
message=England 16-2 (13)
tagline=J Trott(6) I Bell(4)* 
date=19 August, 2012
ver=19

Upvotes: 3

Toby Allen
Toby Allen

Reputation: 11213

use curl or libcurl. It will fetch a webpage for you and you can do whatever you like with it.

Upvotes: 3

Related Questions