我正在使用两个线程,一个正在下载,另一个应该检查下载了多少字节。
这是我的程序的确切代码:
#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;
}
所以这个给出了我想要的结果,但我想这样做而不保存到文件中。