0

我试图找到一种方法来下载文件并让程序等待下载完成然后继续下一个任务,在这种情况下将检查文件是否存在

#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";
    }
}
4

3 回答 3

0

HTTP 请求可能失败。尝试在 /* 总是清理之前添加错误检查 */

if (res)
  cout << curl_easy_strerror(res) << endl;
于 2013-08-17T03:56:18.483 回答
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;
}
于 2013-08-17T06:42:52.337 回答
0

我刚刚意识到,当它使用 ofstream 检查文件是否存在时,它试图写入它,所以它会使文件为空。只需将其从 ofsteam 更改为 fstream 即可完美运行。

于 2013-08-18T01:40:01.890 回答