Note: This article is not the fastest and most efficient code. I have a quick set of code. I hope you can write your own efficient code after reading this article.
Profile
The program uses threads to manage the download process so that the main program is not closed, and the program has the ability to abort the download. The download process is performed separately in the thread and refreshes the status of the taskbar on the screen at any time.
To create a download file:
CInternetSession netsession;
CStdioFile *file;
File = Netsession.openurl (char url,1,internet_flag_transfer_binary | Internet_flag_reload);
function to create a cstdiofile type of file pointer that resides on the local hard drive. Note that some servers may require permission to read and write files.
File Read and write:
file- >Read(char buffer,int bytes to read);
CFile fl;
fl.Open( "myfile ",CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
fl.Write(buffer,bytes read);
task bar, data transmission and others
Task strip with Cprogressctrl::setrange32 (); function, which has a minimum value and a maximum value of two parameters. The minimum value is 0, and the maximum is the file size. The size of the file can be obtained using the following function:
int x = file->seektoend ();
:: The Seektoend () function returns all the bytes of a file, that is, the file size.
The task bar is refreshed once a file packet is read. The file packet is 512 bytes, so that the connection is not blocked. That is, once the file->read () function is executed, the task bar is refreshed:
while(int bytesread = file- >Read(charbuf,512))
{
currentbytes = currentbytes + bytesread;
CProgressCtrl::SetPos(currentbytes);
}
The following code calculates the number of bytes downloaded, percentages, and download speed (KB/SEC):
int percent = Currentbytes * 100/x (file size);
int kbreceived = currentbytes/1024;
Create a COleDateTime object and set the download start time before entering the file download's loop body, and then declare a variable (double) to hold the time difference (in seconds) from the start time in the download process:
COleDateTime Dlstart = Coledatetime::getcurrenttime ();
Double secs;
To calculate the download time (in seconds) with the COleDateTimeSpan object in the download loop:
COleDateTimeSpan dlelapsed = Coledatetime::getcurrenttime ()-Dlstart;
secs = Dlelapsed.gettotalseconds ();
Divide the number of bytes received by the time it takes to get the download rate:
Double kbsec = kbreceived/secs;
This article briefly describes the basic process of tracking file downloads with the task bar. Other details, such as error handling, can be read in the attachment procedure.
Hopefully this article will help you understand the various aspects of downloading files from the Web.