Internet File Downloading Function

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;

          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);


     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 . . .

More by Author

Previous articleDAO ComboBox
Next articleSimple BMP Viewer

Must Read