1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include <iostream> #include <string> #include <curl/curl.h> using namespace std; // Callback function to handle the data received from libcurl size_t writeCallback(void* contents, size_t size, size_t nmemb, string* buffer) { size_t totalSize = size * nmemb; buffer->append((char*)contents, totalSize); return totalSize; } // Function to fetch and display the content from a URL void fetchAndDisplayContent(const string& url) { CURL* curl; CURLcode res; string content; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content); // Perform the request res = curl_easy_perform(curl); if (res != CURLE_OK) { cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl; } else { cout << "Fetched content:\n" << content << endl; } // Cleanup curl_easy_cleanup(curl); } } int main() { string url; cout << "Enter the URL to fetch: "; getline(cin, url); fetchAndDisplayContent(url); return 0; } |
Explanation
- libcurl:
- The program uses the
libcurl
library to handle HTTP requests.libcurl
is a widely used library for transferring data with URLs and supports various protocols, including HTTP and HTTPS.
Advertisement - The program uses the
- writeCallback Function:
- This is a callback function that
libcurl
uses to store the data it receives. It appends the received data to astd::string
Advertisement
- This is a callback function that
- fetchAndDisplayContent Function:
- This function initializes
libcurl
, sets the URL to be fetched, and assigns the callback function to handle the incoming data. - The content fetched from the URL is stored in the
content
string and then displayed.
- This function initializes
- Main Function:
- The
main()
function prompts the user to enter a URL, which is then passed tofetchAndDisplayContent()
to retrieve and display the content.
- The
Notes:
- Limitations: This basic example only handles plain text content and doesn’t parse or render HTML, CSS, or JavaScript. For a fully functional text-based browser, you would need to implement an HTML parser and a text renderer.
- libcurl Installation: You need to have
libcurl
installed and linked to your project. On most Linux distributions, you can install it using a package manager (e.g.,sudo apt-get install libcurl4-openssl-dev
). - Extensions: You could extend this program to support HTML parsing, navigation through hyperlinks, history management, and more to create a more feature-complete text-based browser.
Advertisement