我在 C 中使用 cURL,并且希望将页眉和正文写入内存而不是文件:
static size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
{
int written = fwrite(ptr, size, nmemb, (FILE *)stream);
return written;
}
This thread详细介绍了如何使用 C++ 实现此操作,以及 this thread在 GCC 中执行此操作的详细信息。
据我所知( here 和 here ),在 MVSC 中无法做到这一点 - 或者不容易。
如果不是用 cURL 库的某些函数替换文件流,那么肯定有某种方法可以做到这一点?也许有某种方法可以绕过指向传递的流的指针?我被难住了!
最佳答案
您链接的第一个问题确切地展示了如何做到这一点。你不需要任何花哨的东西。如果您使用 C++,则最好使用 stringstream
。如果没有,您可以使用普通 auld memcpy
附加到缓冲区。
struct buffer {
void *mem;
size_t size;
};
....
struct buffer b = {0};
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &b);
static size_t writeData(void *ptr, size_t size, size_t nmemb, void *data)
{
void *mem;
struct buffer *b = data;
/* Save old size and try to realloc buffer. */
size_t oldsize = b->size;
b->size += size * nmemb;
if (!(mem = realloc(b->mem, b->size))) {
/* realloc failed, handle error. */
}
/* If realloc worked, just append. */
b->mem = mem;
mempy(b->mem + oldsize, ptr, nmemb * size);
}
此代码未经测试,但解决问题应该相当容易。
关于在 MVSC 中为 cURL 创建字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22655248/