我正在使用 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 现在存储在 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());
仍然不适合我;(
最佳答案
binary_file.write(reinterpret_cast<const char*>(&p_Data),sizeof(std::string));
是的,这就是为什么 reinterpret_cast
在很多情况下都很糟糕:它促进了guesscoding。
这是当您扔掉引用资料并假设您需要将指针传递到某个地方的 std::string
时,并确定编译器的错误消息是错误的。因此,您使用 reinterpret_cast
来“闭嘴”,现在您想知道为什么没有任何东西正常工作。
大概有人告诉您“使用 std::string
”而不是 char 数组,而您只是交换了类型名称而不是对实际 区别在于。
std::string
是一个具有各种内部成员的对象,通常间接存储其实际字符串数据(动态地,或者您可能不准确和误导地称为“在堆上”) ;事实上,关于它如何存储数据,它完全不为你所知。无论哪种方式,它都不仅仅是一个 char
数组。
使用它提供的 API 获取指向 char
数组的指针,使用 std::string::data()
或可能使用 std: :string::c_str()
... 和 stop guesscoding .
另外,我怀疑这个编译:
std::string errorBuffer[CURL_ERROR_SIZE];
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
您可能想构造一个具有特定长度的 std::string
:
std::string errorBuffer(CURL_ERROR_SIZE);
curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &errorBuffer[0]);
// ^ (requires C++11 to be completely safe)
字符串是对象,不是原始数组!
关于c++ - 将服务器响应(std::string)转换为 png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7711682/