CURLcode 到 C 中的变量

标签 c curl pthreads

我正在使用两个线程,一个正在下载,另一个应该检查下载了多少字节。

这是我的程序的确切代码:

#include <stdio.h>
#include <curl/curl.h>
#include <curl/easy.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

CURLcode res;
FILE *fp;

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written;
    written = fwrite(ptr, size, nmemb, stream);
    return written;
}

void *downloadThread() {
    CURL *curl;

    char *url = "http://imgsrc.hubblesite.org/hu/db/images/hs-2006-10-a-hires_jpg.jpg";
    char outfilename[FILENAME_MAX] = "picture.jpg";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        printf("File download started\n");
        res = curl_easy_perform(curl);
        printf("File download finished\n");
        curl_easy_cleanup(curl);
        //fclose(fp);
    }
}

void *checkThread() {
    while(1) {
        int prev=ftell(fp);
        fseek(fp, 0L, SEEK_END);
        int downloadedFile=ftell(fp);
        fseek(fp,prev,SEEK_SET); //go back to where we were
        //int downloadedFile = 0; /* instead of 0 it should be something with "res" variable */
        printf("The file size is  %d\n", downloadedFile);
        usleep(1000000);    
    }
}

void setThread() {
    //Thread settings
    pthread_t tid1, tid2;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_create(&tid1,&attr,downloadThread, NULL);
    pthread_create(&tid2,&attr,checkThread, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
}

int main() {
    setThread();
    return 0;
}

所以这个给出了我想要的结果,但我想这样做而不保存到文件中。

最佳答案

像这样修改 write_function 怎么样?

time_t start_time = time(0); 
size_t bytes_downloaded = 0;

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    time_t current_time = time(0);
    time_t elapsed_time = current_time - start_time;

    // do you still need it?
    // size_t written;
    // written = fwrite(ptr, size, nmemb, stream);

    bytes_downloaded += (size * nmemb);

    printf("Bytes downloaded %u in %u seconds at %u bytes/sec\n", 
            bytes_downloaded, elapsed_time, bytes_downloaded / elapsed_time);

    return (size * nmemb);
}

关于CURLcode 到 C 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13928487/

相关文章:

c - 从文件读取到数组 - C

c - 如何测试我的 gstreamer 插件?是否有用于 gstreamer 插件测试的标准测试套件?

curl - iCloud 日历请求

c++ - 尽管尝试创建两个线程,但只创建了一个线程

c - 使用互斥体和 Pthread 库的错误输出

c - C 是否要求在作用域开始时声明变量?

c++ - C 文件* 到 ostream/istream

c++ - 如何发出 libcurl HTTP Web 请求?

javascript - 如何通过原型(prototype) Ajax.Request() 传递 HTTP AUTH 值?

c - gdb 没有正确打印字符串值