[英]How can i create an accurate output buffer in C++ for 7zip command line output?
[英]How to create if statement from curl command output (c++)
我試圖讓curl
命令的 output 在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 獲取文件的內容,該文件本身有一個單行。
std::system
返回一個具有實現定義值的int
。 在許多平台上, 0
意味着成功,其他任何東西都意味着某種失敗。 我在下面的例子中做了這個假設。
我的建議是使用curl
命令在內部使用的libcurl 。 通過一些設置,您可以使您的程序執行curl
操作並接收您返回到程序中的內容。 If you do not have access to libcurl or find it a bit hard to get started with, you could wrap your system
command in a function which performs the curl
command but directs the output to a temporary file which you read after curl
is done.
例子:
#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
function 您可以執行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';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.