c++ libcurl get request is returning 0 but still printing in the console
I've installed libcurl on ubuntu 20.4 and I've been playing around with it. I decidedly wanted to create a program that would write a file from the internet. So I wrote this.
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <fstream>
#include <unistd.h>
int main() {
std::ofstream htmlFile("index.html");
auto curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/");
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
htmlFile <<curl_easy_perform(curl);
htmlFile.close();
}
return 0;
}
When I run this file I'm given my apache webserver html code through the console. But when looking at the file I want to write to there's just a zero.
I'm stumped, I've seen so many different ways to do this. I find it strange that the html is logged to the console, but all it does is return 0.
curl_easy_perform
returns a CURLcode
. where "CURLE_OK
(0
) means everything was ok". That's what is written to your file.
If you want to capture the text inside the program, you need to set a callback function with CURLOPT_WRITEFUNCTION
and also provide somewhere to store the data via CURLOPT_WRITEDATA
Example:
#include <curl/curl.h>
#include <fstream>
#include <string>
size_t write_callback(char* ptr, size_t size, size_t nmemb, void* userdata) {
std::string& data = *static_cast<std::string*>(userdata);
size_t len = size * nmemb;
// append to the string:
data.append(ptr, len);
return len;
}
int main() {
auto curl = curl_easy_init();
if(curl) {
std::string data; // we'll store the data in a string
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/");
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L);
// provide a pointer to where you'd like to store the data:
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
// provide a callback function:
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
if(curl_easy_perform(curl) == CURLE_OK) {
std::ofstream htmlFile("index.html");
if(htmlFile)
htmlFile << data; // all's well, store the data in the file.
}
curl_easy_cleanup(curl);
}
}