我试图找到一种方法来下载文件并让程序等待下载完成然后转到下一个任务,在这种情况下将检查文件是否存在
#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <fstream>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
using namespace std;
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://199.91.153.180/y1plsynnb11g/e9g9mcd3fi5txov/UHC.jar";
char outfilename[FILENAME_MAX] = "UHC.jar";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, "http://199.91.153.180/y1plsynnb11g/e9g9mcd3fi5txov/UHC.jar");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
ofstream launch;
launch.open("UHC.jar");
if (launch.is_open()){
cout<< "File Downloaded";
}
else {
cout << "Download Failed";
}
}
答案 0 :(得分:0)
HTTP请求可能已失败。尝试在/ *始终清理* /
之前添加错误检查if (res)
cout << curl_easy_strerror(res) << endl;
答案 1 :(得分:0)
我意识到write_data的返回值是错误的。但它应该导致错误...... 无论如何,请尝试:
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written * size;
}
答案 2 :(得分:0)
我刚刚意识到在检查使用ofstream存在的文件时出了什么问题,它试图写入它,因此它会使文件为空。只需将它从步骤更改为fstream即可完美运行。