C++20 Windows控制台应用如何捕获curl输出用于if语句判断
问题根因
system()函数的返回值是命令的退出状态码(执行成功返回0,失败返回非0),不是curl命令的标准输出内容,你把退出码转成字符串当然匹配不到响应内容- 原有代码还存在变量名拼写错误:if判断里用的
krxcrlstr没有定义
方案1:使用_popen捕获curl命令输出
该方案不需要引入第三方库,依赖系统自带的curl.exe(Windows 10 1809及以上版本默认自带curl)
#include <iostream> #include <string> #include <cstdio> int main() { // 执行curl命令,加-s参数开启静默模式,只返回响应体,不输出进度、错误信息 FILE* pipe = _popen("curl -s localhost/file.txt", "r"); if (!pipe) { std::cerr << "执行curl命令失败" << std::endl; return 1; } char buffer[128]; std::string response; // 读取命令输出存入string变量 while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { response += buffer; } // 关闭管道 _pclose(pipe); // 字符串匹配逻辑 if (response.find("hello") != std::string::npos) { std::cout << "hello\n"; } else if (response.find("hello2") != std::string::npos) { std::cout << "hello2\n"; } return 0; }
注意事项:如果你的系统没有自带curl,需要把curl.exe所在路径加到系统环境变量,或者在命令里写全curl的绝对路径。
方案2:使用libcurl库(推荐正式项目使用)
该方案不依赖系统curl环境,稳定性更高,适合长期维护的项目。使用前需要先下载libcurl的Windows预编译包,配置到项目中:添加头文件目录、链接libcurl.lib、运行时带上对应libcurl.dll即可。
#include <iostream> #include <string> #include <curl/curl.h> // 回调函数,将curl响应内容写入string变量 size_t write_callback(void* contents, size_t size, size_t nmemb, std::string* s) { size_t new_length = size * nmemb; try { s->append((char*)contents, new_length); } catch (std::bad_alloc& e) { return 0; } return new_length; } int main() { CURL* curl = curl_easy_init(); if (!curl) { std::cerr << "curl初始化失败" << std::endl; return 1; } std::string response; curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/file.txt"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); // 执行HTTP请求 CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { std::cerr << "请求失败: " << curl_easy_strerror(res) << std::endl; curl_easy_cleanup(curl); return 1; } curl_easy_cleanup(curl); // 字符串匹配逻辑 if (response.find("hello") != std::string::npos) { std::cout << "hello\n"; } else if (response.find("hello2") != std::string::npos) { std::cout << "hello2\n"; } return 0; }
内容的提问来源于stack exchange,提问作者fhc
相关产品推荐
相关产品推荐

