Qt 文本文件的读写操作

二进制文件的读写文件可以使用QFile类、QStream

文本文件的读写建议使用QTextStream类,它操作文件更加方便。

打开文件时,需要参数指定打开文件的模式:

模式

描述

QIODevice::NotOpen

0x0000

不打开

QIODevice::ReadOnly

0x0001

只读方式

QIODevice::WriteOnly

0x0002

只写方式,如果文件不存在则会自动创建文件

QIODevice::ReadWrite

ReadOnly | WriteOnly

读写方式

QIODevice::Append

0x0004

此模式表明所有数据写入到文件尾

QIODevice::Truncate

0x0008

打开文件之前,此文件被截断,原来文件的所有数据会丢失

QIODevice::Text

0x0010

读的时候,文件结束标志位会被转为’\n’;写的时候,文件结束标志位会被转为本地编码的结束为,例如win32的结束位’\r\n’

QIODevice::UnBuffered

0x0020

不缓存

QIODevice::Text在读写文本文件时使用,这样可以自动转化换行符为本地换行符。


(1)写入文本文件

QFile f("c:\\test.txt");
if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
{
    cout << "Open failed." << endl;
    return -1;
}

QTextStream txtOutput(&f);
QString s1("123");
quint32 n1(123);

txtOutput << s1 << endl;
txtOutput << n1 << endl;

f.close();

写入的文件内容为:
123
123


(2)读取文本文件

QFile f("c:\\test.txt");
if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
{
    cout << "Open failed." << endl;
    return -1;
}

QTextStream txtInput(&f);
QString lineStr;
while(!txtInput.atEnd())
{
    lineStr = txtInput.readLine();
    cout << lineStr << endl;
}

f.close();

屏幕打印的内容为:
123

123

QTextStream的流操作符

本文福利, 免费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT图像绘制,QT网络,QT数据库编程,QT项目实战,QT嵌入式开发,Quick模块等等)↓↓↓↓↓↓见下面↓↓文章底部点击免费领取↓↓

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用QtQtCore和QtXml模块来XML文件。下面是一个简单的示例代码,展示了如何使用Qt取XML文件和入XML文件: ```cpp #include <QtXml/QtXml> #include <QtCore/QFile> #include <QtCore/QIODevice> int main() { // 取XML文件 QFile file("example.xml"); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Failed to open XML file for reading."; return -1; } QDomDocument doc; if (!doc.setContent(&file)) { qDebug() << "Failed to parse XML."; file.close(); return -1; } file.close(); // 遍历XML数据 QDomElement root = doc.documentElement(); QDomNodeList nodes = root.childNodes(); for (int i = 0; i < nodes.count(); i++) { QDomNode node = nodes.at(i); if (node.isElement()) { QDomElement element = node.toElement(); qDebug() << "Element name:" << element.tagName(); qDebug() << "Element value:" << element.text(); } } // 入XML文件 QFile outputFile("output.xml"); if (!outputFile.open(QIODevice::WriteOnly)) { qDebug() << "Failed to open output XML file."; return -1; } QTextStream stream(&outputFile); doc.save(stream, 4); // 缩进为4个空格 outputFile.close(); return 0; } ``` 上述示例代码首先打开一个XML文件进行取,然后使用`QDomDocument`类解析XML数据。通过遍历`QDomDocument`对象的子节点,可以获得每个元素的标签名和文本值。最后,将解析后的XML数据保存到新的XML文件中。 请注意,上述代码中使用的XML文件名为"example.xml"和"output.xml",你可以根据自己的需要修改这些文件名。此外,你需要在.pro文件中添加`QT += xml`以包含QtXml模块。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值