Search code examples
c++qtqnetworkaccessmanagerqtnetworkqftp

Qt 4.7 - How to iterate through files in an FTP directory


I have a program in which I have a constant path for an ftp directory. I have a function that needs to access that directory and do some operations on the files within. Before, there was only ever one file in this directory and it always had the same name, so I was told it would be OK to hard-code the path in. In that format, this worked:

void MyClass::FTPReader() { QString filepath = "ftp://user:[email protected]/needed_directory/needed_file.txt"; QNetworkAccessManager *nam = new QNetworkAccessManager(this); QNetworkRequest request(filepath); QNetworkReply *reply = nam->get(request); //Other operations done on data after this... }

However, now it turns out that a) there can be more than one file in this directory, and b) they can have variable names. I do know I will always need all files in the directory, but I don't know the number or the names. Is there any way to loop through the ftp directory (in this case needed_directory and use the network request and reply to get the files individually? I think it probably needs to do the same as above, just without the file-specific part of filename, and then do something with that, but I'm sort of lost how to do that. Thanks!


Solution

  • You can use QFtp. For retrieving the list of files in a directory you can use QFtp::list function. When QFtp::list has been called, the listInfo signal is emitted once for each directory entry. It can be done like:

    QFtp ftp;
    connect( &ftp,SIGNAL(listInfo(QUrlInfo)),this,SLOT(ftpListInfo(QUrlInfo)) );
    ftp.connectToHost( "ftp://user:[email protected]/needed_directory" );
    
    if( ftp.state() == QFtp::LoggedIn )
      ftp.list();
    
    void FtpDialog::ftpListInfo( const QUrlInfo&info )
    {
       if( info.isFile() )
          qDebug() << info.name();
    }