c++qtqt5qhash

How to store Qfile in Qhash


I want to write the data to many different files randomly, So I store the QFile * to Qhash, But it seams not work. and there is a report

QObject::connect: No such signal QObject::aboutToClose() in ....\include\QtCore\5.3.2\QtCore/private/../../../../../src/corelib/io/qtextstream_p.h:75

Could you help me to solve this problem?

Here is a test code to realize my idea.

#include <QHash>
#include <QString>
#include <QFile>
#include <QTextStream>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
QHash <qint32,QFile *> fileHandHash;
for(qint32 i=0; i<1000; i++){
qint32 id = i % 10;
qDebug() << i << "\t" << id;

if( ! fileHandHash.contains(id) ){
QString filename = id + ".out.txt";
QFile MYFILE(filename);
MYFILE.open(QIODevice::WriteOnly);
fileHandHash.insert(id,&MYFILE);
}

QTextStream OUT(fileHandHash.value(id));
OUT << i << "\n";
}
return 1;
}

Solution

  • As said in the comment, you can't store pointers to local variables. However this may be more or less what you're looking for:

    #include <QHash>
    #include <QString>
    #include <QFile>
    #include <QTextStream>
    #include <QFile>
    #include <QDebug>
    
    int main(int argc, char* argv[])
    {
       QHash <qint32, QFile*> fileHandHash;
    
       for (qint32 i = 0; i < 1000; i++) {
          qint32 id = i%10;
          qDebug() << i << "\t" << id;
    
          if(!fileHandHash.contains(id)) {
             QString filename = QString("%1.out.txt").arg(id);
             QFile* myfile = new QFile(filename);
             myfile->open(QIODevice::WriteOnly);
             fileHandHash.insert(id, myfile);
          }
    
          QTextStream out(fileHandHash.value(id));
          out << i << "\n";
       }
    
       qDeleteAll(fileHandHash);
       fileHandHash.clear();
    
       return 1;
    }
    

    Pay attention to the number of file descriptors. Doing this each file will have an open descriptor while in the hash.