在网上搜了一下:
结果如下
From: Daniel Stenberg <daniel_at_haxx.se>
Date: Sun, 28 May 2006 01:17:57 +0200 (CEST)
Date: Sun, 28 May 2006 01:17:57 +0200 (CEST)
On Sun, 28 May 2006, skylark liu wrote:
> I use libcurl to download a file (like abc.jpg) via libcurl. But I
> found the jpg file cannot be open. And the MP3 file also connot be
> played. I check their file size. They differ from their original file
> size. My code is as follows. Do I miss something? Thanks a lot.
> bodyfile = fopen(bodyfilename,"w");
You on Windows? If so, you didn't write the file as binary properly.
-- Commercial curl and libcurl Technical Support: http://haxx.se/curl.htmlReceived on 2006-05-28
didn't write the file as binary properly.
不能就是二进制问,写文件的时候以二进制方式写就行了.
这里我写了一个类(还未写完整):
#include <iostream>
#include <stdio.h>
#include <curl/curl.h>
#include <string>
#include <algorithm>
#include <exception>
using namespace std;
class FileDownloader
{
public:
private:
string fileUrl;
string fileName;
/* string getExtensionName(void)
{
if(this->fileUrl.empty())
{
cout<<"the url of the file is empty!"<<endl;
return "";
}
string::reverse_iterator headIter = fileUrl.rbegin();
string::reverse_iterator tailIter = fileUrl.rend();
string::reverse_iterator iter = headIter;
string extension;
while(iter != tailIter)
{
if(*iter=='.')
{
break;
}
}
iter--;
while(1)
{
extension.push_back(*iter);
if(iter==headIter)
{
break;
}
iter--;
}
return extension;
}
*/
string getFullFileName(void)
{
if(this->fileUrl.empty())
{
cout<<"the url of the file is empty!"<<endl;
return "";
}
string::reverse_iterator headIter = fileUrl.rbegin();
string::reverse_iterator tailIter = fileUrl.rend();
string::reverse_iterator iter = headIter;
string fileName;
while(iter != tailIter)
{
if(*iter=='/')
{
break;
}
iter++;
}
iter--;
while(1)
{
fileName.push_back(*iter);
if(iter==headIter)
{
break;
}
iter--;
}
return fileName;
}
static size_t writeFileCallBack(char *ptr, size_t size, size_t nmemb, void *userdata)
{
FILE * pFile = (FILE *)userdata;
size_t retSize;
retSize = fwrite(ptr,size,nmemb,pFile);
cout<<size*nmemb<<"bytes"<<" received!"<<endl;
fflush(pFile);
return retSize;
}
public:
FileDownloader(const string url)
{
this->fileUrl = url;
this->fileName= "";
}
size_t Download(string path)
{
cout<<"start download!"<<endl;
this->fileName = getFullFileName();
cout<<fileName;
FILE * file = fopen(fileName.c_str(),"wb+");
CURL * curl = curl_easy_init();
if(!curl)
{
throw "error";
return 0;
}
CURLcode retCode;
curl_easy_setopt(curl,CURLOPT_URL,this->fileUrl.c_str());
curl_easy_setopt(curl,CURLOPT_WRITEDATA,(void *)file);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,&FileDownloader::writeFileCallBack);
retCode = curl_easy_perform(curl);
fclose(file);
return retCode;
}
};
int main()
{
FileDownloader fileDownloader("www.fileden.com/files/2008/7/31/2027793/musics/ToHeart/Feeling%20Heart%20-%20Feeling%20Heart.mp3");
fileDownloader.Download("");
return 0;
}