今天学习了Qt的QDir模块,感觉对于文件的遍历,Qt的容器相当好用。
foreach( )第一个参数是迭代器指针,第二个是容器。
If you just want to iterate over all the items in a container in order, you can use Qt’s foreach keyword. The keyword is a Qt-specific addition to the C++ language, and is implemented using the preprocessor.
Its syntax is: foreach (variable, container) statement. For example, here’s how to use foreach to iterate over aQLinkedList<QString>:
QLinkedList<QString> list; … QString str; foreach (str, list) qDebug() << str;
如果你想有序迭代容器中的所有项可以使用关键字foreach,这是qt对C++的特定补充,并通过预处理器实现。他的语法是:foreach (variable, container) +语句;这儿varible就相当于varible=container.item,只不过这个item会从container的头遍历到尾罢了。
QLinkedList<QString> list;
QLinkedListIterator<QString> i(list); while (i.hasNext()) qDebug() << i.next();
这两个语句达到的目的是一样的。
另外QDir 下面有很多方法很实用,尤其是QFileinfo的很多方法,可以方便的遍历文件夹的文件和子文件夹。配合foreach使用,可以以精简的代码和极高的效率运行。
#include <QtCore/QCoreApplication>
#include <QDebug>
#include <QFileInfo>
#include <QDir>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QDir mQDir(“/home/lzz”);
foreach(QFileInfo m_Item,mQDir.entryInfoList() )
{
if(m_Item.isDir())qDebug()<< “Dir:” <<m_Item.absoluteFilePath();
if(m_Item.isFile())qDebug()<<“File:” <<m_Item.absoluteFilePath();
}
return a.exec();
}