我在尝试使用 libcurl
下载文件时遇到问题。该程序使用多个线程,每个需要下载文件的线程都会创建一个 libcurl
句柄来处理。
当 URL 正确时,一切正常,但如果 URL 中有错误,程序就会崩溃。在 Debug模式下,如果 URL 不正确,curl_easy_perform
会返回一个错误连接代码并且程序可以运行。相反,它在发布时崩溃。
我该如何解决这个错误?
这是我下载文件的代码,无关代码已被抑制:
LoadFileFromServer
(
string& a_sURL
)
{
string sErrorBuffer;
struct DownloadedFile updateFile = { sFilenameToWrite, // name to store the local file if succesful
NULL }; // temp buffer
CURL* pCurl = curl_easy_init();
curl_easy_setopt( pCurl, CURLOPT_URL, a_sURL.data() );
curl_easy_setopt( pCurl, CURLOPT_FOLLOWLOCATION, 1L );
curl_easy_setopt( pCurl, CURLOPT_ERRORBUFFER, sErrorBuffer );
curl_easy_setopt( pCurl, CURLOPT_WRITEFUNCTION, BufferToFile );
curl_easy_setopt( pCurl, CURLOPT_WRITEDATA, &updateFile );
curl_easy_setopt( pCurl, CURLOPT_NOPROGRESS, 0 );
curl_easy_setopt( pCurl, CURLOPT_CONNECTTIMEOUT, 5L );
CURLcode res = curl_easy_perform( pCurl );
curl_easy_cleanup( pCurl );
}
int BufferToFile
(
void * a_buffer,
size_t a_nSize,
size_t a_nMemb,
void * a_stream
)
{
struct DownloadedFile *out = ( struct DownloadedFile * ) a_stream;
if( out && !out->stream )
{
// open file for writing
if ( 0 != fopen_s( &( out->stream ), out->filename.c_str(), "wb" ) )
return -1;
if( !out->stream )
return -1; /* failure, can't open file to write */
}
return fwrite( a_buffer, a_nSize, a_nMemb, out->stream );
}
最佳答案
libcurl 要求给定的 URL 是指向它可以读取的有效缓冲区的指针。如果不是,则错误出在您的代码中。
如果您传递一个指向(零终止)字符串的正确指针,该字符串可以是正确的 URL,也可以不是,但 libcurl 不应因此而崩溃(据我所知它不会)。
关于c++ - curl_easy_perform 在 URL 不正确时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13160290/