QT中的读和写文件的方式也有很多,这是我用到的写和读(QTextStream):
写:
- /*
- * 将注册表子键值写进文件
- */
- void RegistryWindow::writeIntoFileOfKeyValueTable(QString keyName,QString name,QString type,QString data)
- {
- //创建文件夹
- if (!QDir::current().exists("keyValueTable"))
- {
- QDir::current().mkdir("keyValueTable");
- }
- QString re = keyName.replace(QRegExp("\\\\"),"@"); //正则表达式,@来代替分隔
- //创建文件
- QFile file("./keyValueTable/" + re +".txt");
- if(!file.open(QIODevice::WriteOnly|QIODevice::Append))
- {
- QMessageBox::information(this,QStringLiteral("打开文件失败!"),file.errorString());
- }
- QTextStream fileOut(&file);
- // fileOut.setCodec("UTF-8"); //unicode UTF-8 ANSI
- fileOut << name << "$" << type << "$" << data << "\n";
- file.flush();
- file.close();
- }
读:
- /*
- * 将文件中的注册表键值读出,并显示到注册表键值表格上
- */
- void RegistryWindow::readFromFileOfKeyValueTable(QString keyName)
- {
- QString re = keyName.replace(QRegExp("\\\\"),"@");
- //创建文件
- QFile file("./keyValueTable/" + re +".txt");
- //打开文件
- if(!file.open(QIODevice::ReadOnly))
- {
- QMessageBox::information(this,QStringLiteral("打开文件失败!"),file.errorString());
- }
- QTextStream fileIn(&file);
- QString str = fileIn.readLine(0);
- while (str.contains("$"))
- {
- qDebug() << str;
- QStringList strList = str.split("$");
- QTextCodec *codec = QTextCodec::codecForLocale();//显示汉字的
- //最终要存储的键值
- QIcon *resultValueIcon;
- QString resultValueName = strList.at(0);
- QString resultValueType = strList.at(1);
- QString resultValueData = strList.at(2);
- //REG_DWORD类型的键值
- if (QString(resultValueType).contains("REG_DWORD"))
- {
- resultValueIcon = new QIcon(":/Images/Resources/reg_011110.png");
- }
- //REG_BINARY类型的键值
- else if (QString(resultValueType).contains("REG_BINARY"))
- {
- resultValueIcon = new QIcon(":/Images/Resources/reg_011110.png");
- }
- //REG_SZ\REG_EXPAND_SZ\REG_MULTI_SZ类型的键值
- else
- {
- resultValueIcon = new QIcon(":/Images/Resources/reg_ab.png");
- }
- //键值名称
- QTableWidgetItem *itemName = new QTableWidgetItem;
- itemName->setIcon(*resultValueIcon);
- itemName->setText(resultValueName);
- //itemName->setText(codec->toUnicode(keyInfo.valueName));
- //键值类型
- QTableWidgetItem *itemType = new QTableWidgetItem;
- itemType->setText(resultValueType);
- //键值数据
- QTableWidgetItem *itemData = new QTableWidgetItem;
- itemData->setText(resultValueData);
- myTableWidget->setRowCount(myTableWidget->rowCount()+1);
- myTableWidget->setRowHeight(myTableWidget->rowCount()-1,20);//设置行高
- myTableWidget->setItem(myTableWidget->rowCount()-1,0,itemName);
- myTableWidget->setItem(myTableWidget->rowCount()-1,1,itemType);
- myTableWidget->setItem(myTableWidget->rowCount()-1,2,itemData);
- str = fileIn.readLine(0);
- }
- }
本文介绍了使用QT库中的QTextStream进行文件读写的实现方式。包括如何将注册表键值写入文件及从文件中读取并解析这些键值。通过具体的代码示例展示了文件操作的具体步骤。
635

被折叠的 条评论
为什么被折叠?



