Adam
Adam

Reputation: 115

How to download a file in C++\wxWidgets

How may I download a file in C++ with wxWidgets?

Been googling and everything and nothing shows up! Help appreciated!

Upvotes: 0

Views: 2804

Answers (4)

ForEveR
ForEveR

Reputation: 55897

From HTTP as Andrejs suggest, from FTP using wxFTP

wxFTP ftp;

// if you don't use these lines anonymous login will be used
ftp.SetUser("user");
ftp.SetPassword("password");

if ( !ftp.Connect("ftp.wxwindows.org") )
{
    wxLogError("Couldn't connect");
    return;
}

ftp.ChDir("/pub");
wxInputStream *in = ftp.GetInputStream("wxWidgets-4.2.0.tar.gz");
if ( !in )
{
    wxLogError("Coudln't get file");
}
else
{
    size_t size = in->GetSize();
    char *data = new char[size];
    if ( !in->Read(data, size) )
    {
        wxLogError("Read error");
    }
    else
    {
        // file data is in the buffer
        ...
    }

    delete [] data;
    delete in;
}

http://docs.wxwidgets.org/stable/wx_wxftp.html#wxftp

Upvotes: 1

ravenspoint
ravenspoint

Reputation: 20492

Depends on where you want to 'download' it from, and how the file server allows files to be downloaded. The server might use FTP, or HTTP, or something more obscure. There is no way to tell from your question which has no useful information in it.

In general, I would not use wxWidgets for this task. wxWidgets is a GUI frmaework, with some extras for various things that may or may not be helpful in your case.

Upvotes: 1

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28464

Use wxHTTP class for that.

wxHTTP Example Code:

#include <wx/sstream.h>
#include <wx/protocol/http.h>

wxHTTP get;
get.SetHeader(_T("Content-type"), _T("text/html; charset=utf-8"));
get.SetTimeout(10); // 10 seconds of timeout instead of 10 minutes ...

while (!get.Connect(_T("www.google.com")))
    wxSleep(5);

wxApp::IsMainLoopRunning();

wxInputStream *httpStream = get.GetInputStream(_T("/intl/en/about.html"));

if (get.GetError() == wxPROTO_NOERR)
{
    wxString res;
    wxStringOutputStream out_stream(&res);
    httpStream->Read(out_stream);

    wxMessageBox(res);
}
else
{
    wxMessageBox(_T("Unable to connect!"));
}

wxDELETE(httpStream);
get.Close();

If you want more flexible solution consider using libcurl.

Upvotes: 6

You did not define what "downloading a file" means to you.

If you want to use HTTP to retrieve some content, you should use an HTTP client library like libcurl and issue the appropriate HTTP GET request.

Upvotes: 0

Related Questions