在集合中存储多个QFile的最佳方法是什么?最好使用QList,数组还是向量?
我想以QFile而不是QFile *来访问集合的元素。
我正在尝试读取Qt中的目录并将所有文件存储在集合中。然后将所有文件名打印到屏幕上。
我如何阅读目录:
QDirIterator it(p_dir, QStringList() << "*.wav", QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext())
{
// Put file into collection
}
目前我正在使用QList来存储QFiles:
QList<QFile*> list;
我读到获取文件信息的最佳方法是使用QFileInfo类型。如何将QFileInfo文件设置为列表中的元素?
我想做类似的事情:
QFileInfo info;
QListIterator<QFile*> i(list);
while(i.hasNext())
{
info.setFile(i);
}
但上面给了我: 错误:没有匹配函数来调用'QFileInfo :: setFile(QListIterator&amp;)' fi.setFile(ⅰ);
答案 0 :(得分:1)
请注意QFile
继承QObject
,因此不可复制或移动。通常的做法是在容器中存储指向这些对象的指针而不是对象本身。至于使用哪个容器,它并不重要,但QVector
将是最有效的。
QListIterator
是一个Java风格的迭代器。所以:
QListIterator::QListIterator(const QList<T> & list)
构造用于遍历列表的迭代器。迭代器设置为 在列表的前面(在第一个项目之前)。
迭代器没有指向任何东西,如果你想获得实际的对象,使用i.next()
给你一个QFile*
然后你将不得不取消引用,因为setFile()
接收QFile &
,而不是QFile *
。
答案 1 :(得分:1)
QFile
is not copyable. In C++98, there's generally no way of storing it in a container, unless the container supports in-place construction. I don't know offhand of any such C++98 containers, although writing one wouldn't be all that hard.
In C++11, you can use any container that doesn't need to copy elements and supports emplacement, e.g. std::list
:
// https://github.com/KubaO/stackoverflown/tree/master/questions/qfile-list-36391586
#include <QtCore>
#include <list>
void populate(std::list<QFile> & files) {
QDir dir(QCoreApplication::applicationDirPath());
for (auto fileName : dir.entryList(QDir::Files)) {
qDebug() << "adding file" << fileName;
files.emplace_back(fileName);
}
}
void iterate(std::list<QFile> & files) {
for (auto & file : files)
if (file.open(QIODevice::ReadOnly)) {
qDebug() << "successfully opened" << file.fileName();
}
}
int main(int argc, char ** argv) {
QCoreApplication app(argc, argv);
std::list<QFile> files;
populate(files);
iterate(files);
}
On my system, when run from Qt Creator, the output is:
adding file "main.o"
adding file "Makefile"
adding file "qfile-list-36391586"
successfully opened "main.o"
successfully opened "Makefile"
successfully opened "qfile-list-36391586"
Since QFile
is a proper class implementing RAII of system resources, the files will get automatically closed by files::~list
, before main
returns.
答案 2 :(得分:0)
我目前正在根据某些条件来操作QFileInfon /逻辑。.但是,如果我仅过滤所有复杂的逻辑,它将类似于
QDir testDir("/home/mypath/to/dir");
QFileInfoList files = testDir.entryInfoList(); // #1. here you may use filters as I'm filtering based on a specific file extension
QFileInfoList myfiles;
for(int index = 0; index < files.size(); ++index)
{
const QFileInfo& info = files.at(index);
qDebug() << info.absoluteFilePath() << endl;
// #2. I've some sort of filters I used in #1 above that I compares here by utilizing info here, something like
//if (info.baseName().contains("anyPattern");
myfiles.push_back(info);
}
// Now you can view whatever you stored
for (int vw_idx = 0; vw_idx < myfiles.size(); ++vw_idx)
{
const QFileInfo& info = files.at(index);
qDebug() << info.absoluteFilePath() << endl;
}