我想在visual studio 2013中使用curl库(c ++)下载一些zip文件。使用我的代码进行的下载似乎运行良好,至少这是详细说明的输出。该文件总是比实际文件大一点,文件总是“损坏”,所以我用一些文本文件尝试它,它似乎随机添加一些行在文档的开头/结尾,并使随机空格/破坏形成。这是我的代码的卷曲部分:
//NOTE "CURL *curl" has already been used for previous requests and holds some cookies, so I won't paste the whole code here
//
//write to file function
size_t write_file(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
void download_file(string file_id){
cout << "attempting to download file_id: " << file_id<< "\n";
errno_t err; //error placeholder
FILE * dl_file;
string url = "http://foo.com/"; //base url
string path_to_beatmap_file = "C:\\Users\\foo\\Desktop\\";
string file_extension = ".txt";
string full_filepath = path_to_beatmap_file + beatmap_id + file_extension;
if (curl){
cout << "attempting to download file to: " << full_filepath.c_str() << "\n";
err = fopen_s(&dl_file, full_filepath.c_str(), "w+");
if (err != 0){
cout << "error: could not create file\n";
return;
}
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); //need this since 1 redirect
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_file);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, dl_file);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); //shows some debug output
CURLcode res = curl_easy_perform(curl); //execute download request
}
else{
cout << "error: could not download file, no connection avaible\n";
return;
}
cout << "\n\ndownloaded\n";
if (fclose(dl_file) == 0){ cout << "closed the stream to file"; }
else{ cout << "failed closing file"; }
}
如果我在notepad ++中打开txt文件,它会在文件的结尾处显示一堆空值或子值,但我似乎无法在此处粘贴它们。
非常感谢帮助。
更新 似乎添加的随机文本是一些随机的ASCII字符(我使用调试功能在控制台中打印输出,并且有一些右箭头字符,但我不认为我可以通过删除所有右箭头字符来解决这个问题只要)。有什么想法吗?
答案 0 :(得分:0)
显然在fopen上使用“wb”参数(写二进制)(在fopen_s上也一样)解决了所有格式化问题,现在一切正常。