2012-12-18 65 views
1

我正在使用两个线程,一个正在下载,另一个应该检查下载的字节数。将CURLcode转换为C中的一个变量

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

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

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

+2

'libcurl'站点有不正是这样的例子:HTTP ://curl.haxx.se/libcurl/c/getinmemory.html – qrdl

回答

0

由于qrdl张贴的答案是在这个环节:

curl.haxx.se/libcurl/c/getinmemory.html

1

怎么样修改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); 
} 
+0

这不会是解决方案,因为我正在尝试在下载过程中进行检查。然而,发布的链接qrdl实际上解决了我的问题 –

+0

每次接收到大量数据时都会调用write_data,因此统计数据会不断更新。如果您需要每秒打印一次,您可以将bytes_downloaded和elapsed_time从本地变为全局变量并在第二个线程中打印出来。 –

相关问题