Search code examples
qtqt4qdir

Qt4: How to read data from files in a directory using QDirIterator


Using Qt 4.7, I need to look for a file in a given directory that has a certain name. If it is found, I need to get the text data from within that file. I have the code set up as follows:

    QDirIterator iterator(dir_name, QDirIterator::IteratorFlag);  
    while(iterator.hasNext()  
    { 
        if(iterator.fileName() == nameOfNeededFile)
        {
            //Code need here to get data!
        }
    }

It's also probably worth noting that the directory only contains files, no subdirectories.


Solution

  • as being mentioned in comments you don't need an iterator..

    QByteArray data;
    
    if (QFile::exists("<your file name>")) {
       QFile f("your file");
       if (f.open( QIODevice::ReadOnly )) {
          data = f.readAll();
          f.close();
       }
    }