【发布时间】:2011-10-10 10:47:40
【问题描述】:
我正在使用 boost::asio 收到来自服务器的响应。结果存储在 std::string 中。
我想将此 std::string 转换为 .png 图像并将其写入文件。
我在这方面遇到了严重的麻烦。这是我的代码:
CURL *curl;
CURLcode res;
std::string errorBuffer[CURL_ERROR_SIZE];
std::string url="http://www.google.ie/images/srpr/logo3w.png";
std::string response="";
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_HEADER, 0);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
curl_easy_setopt(curl, CURLOPT_ENCODING, "gzip");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res=curl_easy_perform(curl);
curl_easy_cleanup(curl);
回复现在存储在response
write_to_binary_file(response.data());
,其中 write_to_binary_file 是:
void write_to_binary_file(std::string p_Data){
//std::fstream binary_file("./img.png",std::ios::out|std::ios::binary|std::ios::app);
//binary_file.write(reinterpret_cast<const char*>(&p_Data),sizeof(std::string));
//binary_file.close();
std::ofstream file("img.png", std::ios::binary);
file.write(p_Data,sizeof(p_Data));
file.close();
}
现在,如果我对我的 C++ 程序编写的文件进行八进制转储,它与我直接从 URL 下载文件时得到的八进制转储完全不同。
更新了 write_to_binary_file
int write_to_binary_file(const char* p_Data){
//std::fstream binary_file("./img.png",std::ios::out|std::ios::binary|std::ios::app);
//binary_file.write(reinterpret_cast<const char*>(&p_Data),sizeof(std::string));
//binary_file.write(c_str(),sizeof(ring));
//binary_file.close();
/*std::ofstream file("img.png", std::ios::binary);
file.write(p_Data,len);
file.close();*/
FILE *fp;
size_t count;
const char *str = p_Data;
fp = fopen("img.png", "w");
if(fp == NULL) {
perror("failed to open img.png");
return EXIT_FAILURE;
}
count = fwrite(str, 1, strlen(str), fp);
printf("Wrote %zu bytes. fclose(fp) %s.\n", count, fclose(fp) == 0 ? "succeeded" : "failed");
return EXIT_SUCCESS;
}
使用int x=write_to_binary_file(response.c_str());拨打电话
还是不适合我 ;(
【问题讨论】:
-
errorBuffer的声明和curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);行没有意义。重新阅读该功能的手册。 -
sizeof(std::string)大错特错。您是否使用reinterpret_cast是因为编译器就像“哦,上帝,不要将 p_Data 转换为那个”? -
@todda.speot.is 是的,我把它从互联网上撤下来了……你能就如何解决问题提出建议吗?
-
什么是“响应”?你为什么要把它转换成字符串?
-
嗨亚历山德罗 - “响应”是一个 std::string