Fork me on GitHub

libcurl上传文件崩溃

参考的官网demo写了上传文件的代码。

https://curl.se/libcurl/c/fileupload.html

#include <stdio.h>
#include <curl/curl.h>
#include <sys/stat.h>
#include <fcntl.h>
 
int main(void)
{
  CURL *curl;
  CURLcode res;
  struct stat file_info;
  curl_off_t speed_upload, total_time;
  FILE *fd;
 
  fd = fopen("debugit", "rb"); /* open file to upload */
  if(!fd)
    return 1; /* cannot continue */
 
  /* to get the file size */
  if(fstat(fileno(fd), &file_info) != 0)
    return 1; /* cannot continue */
 
  curl = curl_easy_init();
  if(curl) {
    /* upload to this place */
    curl_easy_setopt(curl, CURLOPT_URL,
                     "file:///home/dast/src/curl/debug/new");
 
    /* tell it to "upload" to the URL */
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
 
    /* set where to read from (on Windows you need to use READFUNCTION too) */
    curl_easy_setopt(curl, CURLOPT_READDATA, fd);
 
    /* and give the size of the upload (optional) */
    curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                     (curl_off_t)file_info.st_size);
 
    /* enable verbose for easier tracing */
    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
 
    res = curl_easy_perform(curl);
    /* Check for errors */
    if(res != CURLE_OK) {
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));
    }
    else {
      /* now extract transfer info */
      curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD_T, &speed_upload);
      curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME_T, &total_time);
 
      fprintf(stderr, "Speed: %lu bytes/sec during %lu.%06lu seconds\n",
              (unsigned long)speed_upload,
              (unsigned long)(total_time / 1000000),
              (unsigned long)(total_time % 1000000));
    }
    /* always cleanup */
    curl_easy_cleanup(curl);
  }
  fclose(fd);
  return 0;
}

  在windows下实测会崩溃。

       当时写的时候就纳闷,为啥不用写ReadFunction,只需要写ReadData传递文件句柄?

       补上

       curl_easy_setopt(curl, CURLOPT_READFUNCTION, &fread);

       正常了。


posted @ 2024-07-29 10:46  烟波--钓徒  阅读(12)  评论(0编辑  收藏  举报