赞
踩
- #include <QtCore/QCoreApplication>
- #include <QXmlStreamWriter>
- #include <QFile>
- #include <QDebug>
- #include <QDir>
- #include <QTime>
-
- struct FileStat{
- //文件名
- QString fileName;
- //文件大小
- QString fileSize;
- //上次修改时间
- QString atTime;
- //文件类型
- QString fileType;
- };
-
- typedef QList<FileStat> StatList;
-
- int main(int argc, char *argv[])
- {
- QCoreApplication a(argc, argv);
-
- //QList
- StatList fileList;
-
- //遍历C盘根目录下的文件文件夹,并将属性保存到list中
- QDir dir("c:/");
- dir.setFilter(QDir::Files|QDir::Dirs);
- foreach(QFileInfo fInfo, dir.entryInfoList())
- {
- //排除当前目录和上级目录
- if(fInfo.fileName().left(1) == ".")
- {
- continue;
- }
-
- FileStat fStat;
- fStat.fileName = fInfo.fileName();
- fStat.atTime = fInfo.lastModified().toLocalTime().toString("yyyy-MM-dd hh:mm:ss");
-
- if(fInfo.isDir())
- {
- fStat.fileSize ="0";
- fStat.fileType = "isDir";
- }
- else if(fInfo.isFile())
- {
- QString fileSize = fInfo.size() / 1024 /1024?
- QString::number(fInfo.size() / 1024 /1024)+="MB":
- fInfo.size() / 1024 ?
- QString::number(fInfo.size() / 1024)+="KB" : QString::number(fInfo.size())+="B";
- fStat.fileSize = fileSize;
- fStat.fileType ="isFile";
- }
-
- fileList.append(fStat);
- }
-
- //---------------------------------------------------xml文件写入
- int id = 1;
- QFile file("out.xml");
- if(file.open(QIODevice::WriteOnly|QIODevice::Text))
- {
- QXmlStreamWriter writer(&file);
-
- writer.setAutoFormatting(true);
- //设置自动缩进大小
- writer.setAutoFormattingIndent( 2 );
- //写入xml文档头,一般为: \<?xml version="1.0" encoding="UTF-8"?>\
- writer.writeStartDocument();
- //写入开始标记FileMsg
- writer.writeStartElement("FileMsg");
-
- //循环将容器中的数据写入到xml文件
- StatList::Iterator it = fileList.begin();
- for(;it != fileList.end();it++)
- {
- //写入开始标记DATA
- writer.writeStartElement("DATA");
- //在开始标记中写入属性ID
- writer.writeAttribute("ID",QString::number(id++,10));
- //写入文本信息
- writer.writeTextElement("FILENAME",it->fileName);
- writer.writeTextElement("FILESIZE",it->fileSize);
- writer.writeTextElement("LASTMODIFY",it->atTime);
- writer.writeTextElement("FILETYPE",it->fileType);
- //写入结束标记DATA
- writer.writeEndElement();
- }
- //写入结束标记FileMsg
- writer.writeEndElement();
- //xml文档结束
- writer.writeEndDocument();
-
- //关闭文件
- file.close();
- }
- else
- {
- qDebug()<<"Open File Failure";
- }
- //----------------------------------------------------xml文件写入结束
-
- return a.exec();
- }
//QXmlStreadWriter的使用效果如图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。