dcsimg
 

Internet File Downloading Function

Thursday Dec 9th 1999 by Andon M. Coleman

Simple Function to Download Files From the Internet

Are you looking for a simple method to download a file from the net? One with error checking and all? Well, this is by far one of the most well written function for just such an occasion I've ever written.

Yes, it does lack File Size detection among other things, but that can be easily added . . .


CString GetFile(const char *url, const char *filename)
{
     #define HTTPBUFLEN    512 // Size of HTTP Buffer...
     char httpbuff[HTTPBUFLEN];
     TCHAR   szCause[255];
     CString Cause;
     Cause.Format("YES");
 
     TRY
     {
          CInternetSession mysession;
          CStdioFile *remotefile = mysession.OpenURL(url,1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD);
 
          CFile myfile(filename, CFile::modeCreate|CFile::modeWrite|CFile::typeBinary);
          int numbytes;
 
          while (numbytes = remotefile->Read(httpbuff, HTTPBUFLEN))
               myfile.Write(httpbuff, numbytes);
     }
 
     CATCH_ALL(error)
     {
          error->GetErrorMessage(szCause,254,NULL);
          Cause.Format("%s",szCause);
     }
     END_CATCH_ALL;
 
     return (Cause);
}
This will return a "YES" if all goes right, and if not, you can simply MessageBox(); the return value, since MFC's errors are usually pretty self-explanatory :) Also, I recommend making HTTPBUFLEN and httpbuff into global values . . . That way they can be changed on the fly . . . You could even make HTTPBUFLEN into a function defined value.

In any case this small function should deliver quite an easy / cost effective solution for downloading files . . .

Home
Mobile Site | Full Site
Copyright 2018 © QuinStreet Inc. All Rights Reserved