如何在Qhash中存储Qfile

How to store Qfile in Qhash

我想将数据随机写入多个不同的文件,所以我将QFile * 存储到Qhash,但它接缝不起作用。并且有一份报告

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

你能帮我解决这个问题吗?

下面是实现我想法的测试代码

#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;
}

如评论中所述,您不能存储指向局部变量的指针。然而,这可能或多或少是您要找的东西:

#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;
}

注意文件描述符的数量。这样做每个文件在散列中都会有一个打开的描述符。