我試圖讓curl命令的輸出在一個if statement
我是 C 的新手,不知道如何做到這一點。
int curlreq;
curlreq = system("curl localhost/file.txt");
string curlreqstring = to_string(curlreq);
if ((krxcrlstr.find("hello") != string::npos) ) {
cout << "hello\n";
}
else if (curlreqstring.find("hello2") != string::npos) {
cout << "hello2\n";
}
我正在 Windows 上執行此操作。該專案是一個控制臺應用程式 C 20
上面的所有代碼都在做,正在列印 curl 回應是什么,但我需要它作為一個變數來確定程式應該做什么。
如您所見,我正在從 localhost 獲取檔案的內容,檔案本身只有一行。
uj5u.com熱心網友回復:
std::system回傳int具有實作定義值的 。在許多平臺上,0意味著成功,其他任何事情都意味著某種失敗。我在下面的例子中做出了這個假設。
我的建議是使用 卷曲這是curl命令在內部使用的內容。通過一些設定,您可以讓您的程式執行curl操作并接收您回傳到程式中的內容。如果您無權訪問卷曲或者發現它有點難以開始,您可以將您的system命令包裝在一個函式中,該函式執行該curl命令但將輸出定向到一個臨時檔案,您在curl完成后閱讀該檔案。
例子:
#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
使用上述Curl功能,您可以執行curl命令并獲得回應,std::string然后您可以在if陳述句等中使用它。
例子:
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';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/367012.html
