std::system
vrátí int
s implementací definované hodnoty. Na mnoho platforem, 0
znamená úspěch a nic jiného znamená, že nějaký druh selhání. Dělám tento předpoklad v příkladu níže.
Moje rada je použít curl což je to, co curl
příkaz používá interně. S trochou nastavení si můžete vytvořit svůj program provádět curl
akce a přijímat to, co se dostanete zpět do vašeho programu. Pokud nemáte přístup k libcurl , nebo najít to trochu těžké začít s, můžete zabalit vaše system
příkaz ve funkci, která provádí curl
příkaz, ale přesměruje výstup do dočasného souboru, který jste si po curl
je hotovo.
Příklad:
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
// a simple class to remove the temporary file after use
struct file_to_remove {
// remove "filename" when the object is destroyed
~file_to_remove() { std::remove(filename.c_str()); }
const std::string& str() const { return filename; }
const std::string filename;
};
// A function to "curl":
std::string Curl(std::string options_plus_url) {
// An instance to remove the temporary file after use.
// Place it where you have permission to create files:
file_to_remove tempfile{"tmpfile"};
// build the command line
// -s to make curl silent
// -o to save to a file
options_plus_url = "curl -so " + tempfile.str() + " " + options_plus_url;
// perfom the system() command:
int rv = std::system(options_plus_url.c_str());
// not 0 is a common return value to indicate problems:
if(rv != 0) throw std::runtime_error("bad curl");
// open the file for reading
std::ifstream ifs(tempfile.str());
// throw if it didn't open ok:
if(!ifs) throw std::runtime_error(std::strerror(errno));
// put the whole file in the returned string:
return {std::istreambuf_iterator<char>(ifs),
std::istreambuf_iterator<char>{}};
} // tmpfile is removed when file_to_remove goes out of scope
S výše Curl
funkce, které můžete provádět curl
příkazy a dostanete odpověď jako std::string
které pak můžete použít ve vašem if
prohlášení atd.
Příklad:
int main(int argc, char* argv[]) {
if(argc < 2) return 1; // must get an URL as argument
try {
std::string response = Curl(argv[1]);
std::cout << response << '\n';
} catch(const std::exception& ex) {
std::cout << "Exception: " << ex.what() << '\n';
}
}