Version: 3.1.1
wxFTP Class Reference

#include <wx/protocol/ftp.h>

+ Inheritance diagram for wxFTP:

Detailed Description

wxFTP can be used to establish a connection to an FTP server and perform all the usual operations.

Please consult the RFC 959 (http://www.w3.org/Protocols/rfc959/) for more details about the FTP protocol.

wxFTP can thus be used to create a (basic) FTP client.

To use a command which doesn't involve file transfer (i.e. directory oriented commands) you just need to call a corresponding member function or use the generic wxFTP::SendCommand() method. However to actually transfer files you just get or give a stream to or from this class and the actual data are read or written using the usual stream methods.

Example of using wxFTP for file downloading:

wxFTP ftp;
// if you don't use these lines anonymous login will be used
ftp.SetUser("user");
ftp.SetPassword("password");
if ( !ftp.Connect("ftp.wxwidgets.org") )
{
wxLogError("Couldn't connect");
return;
}
ftp.ChDir("/pub/2.8.9");
const char *filename = "wxWidgets-2.8.9.tar.bz2";
int size = ftp.GetFileSize(filename);
if ( size == -1 )
{
wxLogError("Couldn't get the file size for \"%s\"", filename);
}
wxInputStream *in = ftp.GetInputStream(filename);
if ( !in )
{
wxLogError("Couldn't get the file");
}
else
{
char *data = new char[size];
if ( !in->Read(data, size) )
{
wxLogError("Read error: %d", ftp.GetError());
}
else
{
// file data is in the buffer
...
}
delete [] data;
delete in;
}
// gracefully close the connection to the server
ftp.Close();

To upload a file you would do (assuming the connection to the server was opened successfully):

wxOutputStream *out = ftp.GetOutputStream("filename");
if ( out )
{
out->Write(...); // your data
delete out;
}

Library:  wxNet
Category:  Networking
See also
wxSocketBase

Public Types

enum  TransferMode {
  NONE,
  ASCII,
  BINARY
}
 Transfer modes used by wxFTP. More...
 

Public Member Functions

 wxFTP ()
 Default constructor. More...
 
virtual ~wxFTP ()
 Destructor will close the connection if connected. More...
 
virtual bool Connect (const wxString &host)
 Connect to the FTP server to default port (21) of the specified host. More...
 
virtual bool Connect (const wxString &host, unsigned short port)
 Connect to the FTP server to any port of the specified host. More...
 
Functions for managing the FTP connection
virtual bool Abort ()
 Aborts the download currently in process, returns true if ok, false if an error occurred. More...
 
virtual bool Close ()
 Gracefully closes the connection with the server. More...
 
bool CheckCommand (const wxString &command, char ret)
 Send the specified command to the FTP server. More...
 
const wxStringGetLastResult ()
 Returns the last command result, i.e. More...
 
char SendCommand (const wxString &command)
 Send the specified command to the FTP server and return the first character of the return code. More...
 
bool SetAscii ()
 Sets the transfer mode to ASCII. More...
 
bool SetBinary ()
 Sets the transfer mode to binary. More...
 
void SetPassive (bool pasv)
 If pasv is true, passive connection to the FTP server is used. More...
 
virtual void SetPassword (const wxString &passwd)
 Sets the password to be sent to the FTP server to be allowed to log in. More...
 
bool SetTransferMode (TransferMode mode)
 Sets the transfer mode to the specified one. More...
 
virtual void SetUser (const wxString &user)
 Sets the user name to be sent to the FTP server to be allowed to log in. More...
 
Filesystem commands
bool ChDir (const wxString &dir)
 Change the current FTP working directory. More...
 
bool MkDir (const wxString &dir)
 Create the specified directory in the current FTP working directory. More...
 
wxString Pwd ()
 Returns the current FTP working directory. More...
 
bool Rename (const wxString &src, const wxString &dst)
 Rename the specified src element to dst. More...
 
bool RmDir (const wxString &dir)
 Remove the specified directory from the current FTP working directory. More...
 
bool RmFile (const wxString &path)
 Delete the file specified by path. More...
 
bool FileExists (const wxString &filename)
 Returns true if the given remote file exists, false otherwise. More...
 
bool GetDirList (wxArrayString &files, const wxString &wildcard=wxEmptyString)
 The GetList() function is quite low-level. More...
 
int GetFileSize (const wxString &filename)
 Returns the file size in bytes or -1 if the file doesn't exist or the size couldn't be determined. More...
 
bool GetFilesList (wxArrayString &files, const wxString &wildcard=wxEmptyString)
 This function returns the computer-parsable list of the files in the current directory (optionally only of the files matching the wildcard, all files by default). More...
 
Download and upload functions
virtual wxInputStreamGetInputStream (const wxString &path)
 Creates a new input stream on the specified path. More...
 
virtual wxOutputStreamGetOutputStream (const wxString &file)
 Initializes an output stream to the specified file. More...
 
- Public Member Functions inherited from wxProtocol
virtual wxString GetContentType () const
 Returns the type of the content of the last opened stream. More...
 
virtual wxProtocolError GetError () const
 Returns the last occurred error. More...
 
bool Reconnect ()
 Tries to reestablish a previous opened connection (close and renegotiate connection). More...
 
void SetDefaultTimeout (wxUint32 Value)
 Sets a new default timeout for the network operations. More...
 
void SetLog (wxProtocolLog *log)
 Set the logger, deleting the old one and taking ownership of this one. More...
 
wxProtocolLogGetLog () const
 Return the current logger, may be NULL. More...
 
wxProtocolLogDetachLog ()
 Detach the existing logger without deleting it. More...
 
void LogRequest (const wxString &str)
 Call wxProtocolLog::LogRequest() if we have a valid logger or do nothing otherwise. More...
 
void LogResponse (const wxString &str)
 Call wxProtocolLog::LogResponse() if we have a valid logger or do nothing otherwise. More...
 
- Public Member Functions inherited from wxSocketClient
 wxSocketClient (wxSocketFlags flags=wxSOCKET_NONE)
 Constructor. More...
 
virtual ~wxSocketClient ()
 Destructor. More...
 
virtual bool Connect (const wxSockAddress &address, bool wait=true)
 Connects to a server using the specified address. More...
 
bool Connect (const wxSockAddress &address, const wxSockAddress &local, bool wait=true)
 Connects to a server using the specified address. More...
 
bool WaitOnConnect (long seconds=-1, long milliseconds=0)
 Wait until a connection request completes, or until the specified timeout elapses. More...
 
- Public Member Functions inherited from wxSocketBase
bool Error () const
 Returns true if an error occurred in the last IO operation. More...
 
virtual bool GetLocal (wxSockAddress &addr) const
 Return the local address of the socket. More...
 
virtual bool GetPeer (wxSockAddress &addr) const
 Return the peer address field of the socket. More...
 
long GetTimeout () const
 Return the socket timeout in seconds. More...
 
bool IsConnected () const
 Returns true if the socket is connected. More...
 
bool IsData ()
 Check if the socket can be currently read or written. More...
 
bool IsDisconnected () const
 Returns true if the socket is not connected. More...
 
bool IsOk () const
 Returns true if the socket is initialized and ready and false in other cases. More...
 
wxUint32 LastCount () const
 Returns the number of bytes read or written by the last IO call. More...
 
wxUint32 LastReadCount () const
 Returns the number of bytes read by the last Read() or ReadMsg() call (receive direction only). More...
 
wxUint32 LastWriteCount () const
 Returns the number of bytes written by the last Write() or WriteMsg() call (transmit direction only). More...
 
wxSocketError LastError () const
 Returns the last wxSocket error. More...
 
void RestoreState ()
 Restore the previous state of the socket, as saved with SaveState(). More...
 
void SaveState ()
 Save the current state of the socket in a stack. More...
 
void ShutdownOutput ()
 Shuts down the writing end of the socket. More...
 
wxSocketBaseDiscard ()
 Delete all bytes in the incoming queue. More...
 
wxSocketFlags GetFlags () const
 Returns current IO flags, as set with SetFlags() More...
 
void InterruptWait ()
 Use this function to interrupt any wait operation currently in progress. More...
 
wxSocketBasePeek (void *buffer, wxUint32 nbytes)
 Peek into the socket by copying the next bytes which would be read by Read() into the provided buffer. More...
 
wxSocketBaseRead (void *buffer, wxUint32 nbytes)
 Read up to the given number of bytes from the socket. More...
 
wxSocketBaseReadMsg (void *buffer, wxUint32 nbytes)
 Receive a message sent by WriteMsg(). More...
 
void SetFlags (wxSocketFlags flags)
 Use SetFlags to customize IO operation for this socket. More...
 
virtual bool SetLocal (const wxIPV4address &local)
 Set the local address and port to use. More...
 
void SetTimeout (long seconds)
 Set the default socket timeout in seconds. More...
 
wxSocketBaseUnread (const void *buffer, wxUint32 nbytes)
 Put the specified data into the input queue. More...
 
bool Wait (long seconds=-1, long millisecond=0)
 Wait for any socket event. More...
 
bool WaitForLost (long seconds=-1, long millisecond=0)
 Wait until the connection is lost. More...
 
bool WaitForRead (long seconds=-1, long millisecond=0)
 Wait until the socket is readable. More...
 
bool WaitForWrite (long seconds=-1, long millisecond=0)
 Wait until the socket becomes writable. More...
 
wxSocketBaseWrite (const void *buffer, wxUint32 nbytes)
 Write up to the given number of bytes to the socket. More...
 
wxSocketBaseWriteMsg (const void *buffer, wxUint32 nbytes)
 Sends a buffer which can be read using ReadMsg(). More...
 
void * GetClientData () const
 Returns a pointer of the client data for this socket, as set with SetClientData() More...
 
void Notify (bool notify)
 According to the notify value, this function enables or disables socket events. More...
 
void SetClientData (void *data)
 Sets user-supplied client data for this socket. More...
 
void SetEventHandler (wxEvtHandler &handler, int id=-1)
 Sets an event handler to be called when a socket event occurs. More...
 
void SetNotify (wxSocketEventFlags flags)
 Specifies which socket events are to be sent to the event handler. More...
 
wxSOCKET_T GetSocket () const
 Returns the native socket descriptor. More...
 
 wxSocketBase ()
 Default constructor. More...
 
virtual ~wxSocketBase ()
 Destructor. More...
 
bool Destroy ()
 Destroys the socket safely. More...
 
- Public Member Functions inherited from wxObject
 wxObject ()
 Default ctor; initializes to NULL the internal reference data. More...
 
 wxObject (const wxObject &other)
 Copy ctor. More...
 
virtual ~wxObject ()
 Destructor. More...
 
virtual wxClassInfoGetClassInfo () const
 This virtual function is redefined for every class that requires run-time type information, when using the wxDECLARE_CLASS macro (or similar). More...
 
wxObjectRefDataGetRefData () const
 Returns the wxObject::m_refData pointer, i.e. the data referenced by this object. More...
 
bool IsKindOf (const wxClassInfo *info) const
 Determines whether this class is a subclass of (or the same class as) the given class. More...
 
bool IsSameAs (const wxObject &obj) const
 Returns true if this object has the same data pointer as obj. More...
 
void Ref (const wxObject &clone)
 Makes this object refer to the data in clone. More...
 
void SetRefData (wxObjectRefData *data)
 Sets the wxObject::m_refData pointer. More...
 
void UnRef ()
 Decrements the reference count in the associated data, and if it is zero, deletes the data. More...
 
void UnShare ()
 This is the same of AllocExclusive() but this method is public. More...
 
void operator delete (void *buf)
 The delete operator is defined for debugging versions of the library only, when the identifier WXDEBUG is defined. More...
 
void * operator new (size_t size, const wxString &filename=NULL, int lineNum=0)
 The new operator is defined for debugging versions of the library only, when the identifier WXDEBUG is defined. More...
 

Additional Inherited Members

- Static Public Member Functions inherited from wxSocketBase
static bool Initialize ()
 Perform the initialization needed in order to use the sockets. More...
 
static void Shutdown ()
 Shut down the sockets. More...
 
- Protected Member Functions inherited from wxObject
void AllocExclusive ()
 Ensure that this object's data is not shared with any other object. More...
 
virtual wxObjectRefDataCreateRefData () const
 Creates a new instance of the wxObjectRefData-derived class specific to this object and returns it. More...
 
virtual wxObjectRefDataCloneRefData (const wxObjectRefData *data) const
 Creates a new instance of the wxObjectRefData-derived class specific to this object and initializes it copying data. More...
 
- Protected Attributes inherited from wxObject
wxObjectRefDatam_refData
 Pointer to an object which is the object's reference-counted data. More...
 

Member Enumeration Documentation

Transfer modes used by wxFTP.

Enumerator
NONE 

not set by user explicitly.

ASCII 
BINARY 

Constructor & Destructor Documentation

wxFTP::wxFTP ( )

Default constructor.

virtual wxFTP::~wxFTP ( )
virtual

Destructor will close the connection if connected.

Member Function Documentation

virtual bool wxFTP::Abort ( )
virtual

Aborts the download currently in process, returns true if ok, false if an error occurred.

Implements wxProtocol.

bool wxFTP::ChDir ( const wxString dir)

Change the current FTP working directory.

Returns true if successful.

bool wxFTP::CheckCommand ( const wxString command,
char  ret 
)

Send the specified command to the FTP server.

ret specifies the expected result.

Returns
true if the command has been sent successfully, else false.
virtual bool wxFTP::Close ( )
virtual

Gracefully closes the connection with the server.

Reimplemented from wxSocketBase.

virtual bool wxFTP::Connect ( const wxString host)
virtual

Connect to the FTP server to default port (21) of the specified host.

virtual bool wxFTP::Connect ( const wxString host,
unsigned short  port 
)
virtual

Connect to the FTP server to any port of the specified host.

By default (port = 0), connection is made to default FTP port (21) of the specified host.

Since
2.9.1
bool wxFTP::FileExists ( const wxString filename)

Returns true if the given remote file exists, false otherwise.

bool wxFTP::GetDirList ( wxArrayString files,
const wxString wildcard = wxEmptyString 
)

The GetList() function is quite low-level.

It returns the list of the files in the current directory. The list can be filtered using the wildcard string.

If wildcard is empty (default), it will return all files in directory. The form of the list can change from one peer system to another. For example, for a UNIX peer system, it will look like this:

-r--r--r--   1 guilhem  lavaux      12738 Jan 16 20:17 cmndata.cpp
-r--r--r--   1 guilhem  lavaux      10866 Jan 24 16:41 config.cpp
-rw-rw-rw-   1 guilhem  lavaux      29967 Dec 21 19:17 cwlex_yy.c
-rw-rw-rw-   1 guilhem  lavaux      14342 Jan 22 19:51 cwy_tab.c
-r--r--r--   1 guilhem  lavaux      13890 Jan 29 19:18 date.cpp
-r--r--r--   1 guilhem  lavaux       3989 Feb  8 19:18 datstrm.cpp

But on Windows system, it will look like this:

winamp~1 exe    520196 02-25-1999  19:28  winamp204.exe
    1 file(s)           520 196 bytes
Returns
true if the file list was successfully retrieved, false otherwise.
See also
GetFilesList()
int wxFTP::GetFileSize ( const wxString filename)

Returns the file size in bytes or -1 if the file doesn't exist or the size couldn't be determined.

Notice that this size can be approximative size only and shouldn't be used for allocating the buffer in which the remote file is copied, for example.

bool wxFTP::GetFilesList ( wxArrayString files,
const wxString wildcard = wxEmptyString 
)

This function returns the computer-parsable list of the files in the current directory (optionally only of the files matching the wildcard, all files by default).

This list always has the same format and contains one full (including the directory path) file name per line.

Returns
true if the file list was successfully retrieved, false otherwise.
See also
GetDirList()
virtual wxInputStream* wxFTP::GetInputStream ( const wxString path)
virtual

Creates a new input stream on the specified path.

You can use all but the seek functionality of wxStreamBase. wxStreamBase::Seek() isn't available on all streams. For example, HTTP or FTP streams do not deal with it. Other functions like wxStreamBase::Tell() are not available for this sort of stream, at present.

You will be notified when the EOF is reached by an error.

Returns
Returns NULL if an error occurred (it could be a network failure or the fact that the file doesn't exist).

Implements wxProtocol.

const wxString& wxFTP::GetLastResult ( )

Returns the last command result, i.e.

the full server reply for the last command.

virtual wxOutputStream* wxFTP::GetOutputStream ( const wxString file)
virtual

Initializes an output stream to the specified file.

The returned stream has all but the seek functionality of wxStreams. When the user finishes writing data, he has to delete the stream to close it.

Returns
An initialized write-only stream. Returns NULL if an error occurred (it could be a network failure or the fact that the file doesn't exist).
bool wxFTP::MkDir ( const wxString dir)

Create the specified directory in the current FTP working directory.

Returns true if successful.

wxString wxFTP::Pwd ( )

Returns the current FTP working directory.

bool wxFTP::Rename ( const wxString src,
const wxString dst 
)

Rename the specified src element to dst.

Returns true if successful.

bool wxFTP::RmDir ( const wxString dir)

Remove the specified directory from the current FTP working directory.

Returns true if successful.

bool wxFTP::RmFile ( const wxString path)

Delete the file specified by path.

Returns true if successful.

char wxFTP::SendCommand ( const wxString command)

Send the specified command to the FTP server and return the first character of the return code.

bool wxFTP::SetAscii ( )

Sets the transfer mode to ASCII.

It will be used for the next transfer.

bool wxFTP::SetBinary ( )

Sets the transfer mode to binary.

It will be used for the next transfer.

void wxFTP::SetPassive ( bool  pasv)

If pasv is true, passive connection to the FTP server is used.

This is the default as it works with practically all firewalls. If the server doesn't support passive mode, you may call this function with false as argument to use an active connection.

virtual void wxFTP::SetPassword ( const wxString passwd)
virtual

Sets the password to be sent to the FTP server to be allowed to log in.

Reimplemented from wxProtocol.

bool wxFTP::SetTransferMode ( TransferMode  mode)

Sets the transfer mode to the specified one.

It will be used for the next transfer.

If this function is never called, binary transfer mode is used by default.

virtual void wxFTP::SetUser ( const wxString user)
virtual

Sets the user name to be sent to the FTP server to be allowed to log in.

Reimplemented from wxProtocol.