C写的网络下载

learningman 6月 08, 2018

想从一个Bing壁纸的API抓点图片,懒得装Python,试着用C弄个下载,真的麻烦
VC 6.0编译通过,用Visual Studio的新版本应该一样可以

#include <afx.h>#include <afxinet.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#define RECVPACK_SIZE 2048bool DownloadSaveFiles(char* url,char *strSaveFile) { bool ret=false; CInternetSession Sess("lpload"); Sess.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT , 2000); Sess.SetOption(INTERNET_OPTION_SEND_TIMEOUT , 2000); Sess.SetOption(INTERNET_OPTION_RECEIVE_TIMEOUT , 2000); Sess.SetOption(INTERNET_OPTION_DATA_SEND_TIMEOUT , 2000); Sess.SetOption(INTERNET_OPTION_DATA_RECEIVE_TIMEOUT, 2000); DWORD dwFlag = INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_RELOAD ; CHttpFile* cFile = NULL; char *pBuf = NULL; int nBufLen = 0 ; do { try{ cFile = (CHttpFile*)Sess.OpenURL(url,1,dwFlag); DWORD dwStatusCode; cFile->QueryInfoStatusCode(dwStatusCode); if (dwStatusCode == HTTP_STATUS_OK) { DWORD nLen=0; cFile->QueryInfo(HTTP_QUERY_CONTENT_LENGTH, nLen); nBufLen=nLen; if (nLen <= 0) break; pBuf = (char*)malloc(nLen+8); ZeroMemory(pBuf,nLen+8); char *p=pBuf; while (nLen>0) { int n = cFile->Read(p,(nLen<RECVPACK_SIZE)?nLen:RECVPACK_SIZE); if (n <= 0) break; p+= n ; nLen -= n ; } if (nLen != 0) break; CFile file(strSaveFile, CFile::modeCreate | CFile::modeWrite); file.Write(pBuf,nBufLen); file.Close(); ret = true; } } catch(...) { break; } } while(0); if (pBuf) { free(pBuf); pBuf=NULL; nBufLen = 0 ; } if (cFile) { cFile->Close(); Sess.Close(); delete cFile; } return ret;}int main() { for(int i=1;i<=999;i++) { printf("Test\n"); char after_rename[]="c:\\picture\\001.jpg"; char before_rename[]="c:\\picture\\000.jpg"; char download_name[]="c:\\picture\\000.jpg"; //char* input_name; /*if(i<=100&&i>=10) { after_rename[13]=before_rename[13]+i%10; after_rename[12]=before_rename[12]+i/10; } if(i<10) { after_rename[13]=before_rename[13]+i; }*/ if(i<=1000&&i>=100) { download_name[13]=before_rename[13]+i%10; download_name[12]=before_rename[12]+i/10%10; download_name[11]=before_rename[11]+i/100; } if(i<100&&i>=10) { download_name[13]=before_rename[13]+i%10; download_name[12]=before_rename[12]+i/10; } if(i<10) { download_name[13]=before_rename[13]+i; } printf("Start to download %d pic\n",i); printf("download_name=%s\n",download_name); //printf("input_name=%s\n",input_name); DownloadSaveFiles("https://bing.ioliu.cn/v1/rand?w=1920&h=1080",download_name); //DownloadSaveFiles("https://bing.ioliu.cn/v1/rand?w=1920&h=1080","c:\\picture\\001.jpg"); //printf("Start to rename %d pic\n",i); //printf("nameaf=%s\n",after_rename); /*if(!rename(before_rename,after_rename)) { printf("Success Rename"); } else() printf("Finish %d pic\n",i);*/ } return 0;}

本文采用 CC BY-NC-SA 3.0 协议进行许可,在您遵循此协议的情况下,可以自由共享与演绎本文章。
本文链接:https://learningman.top/archives/394.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注




you're currently offline