首页 > 其他分享 >Qt 读写txt文本文件

Qt 读写txt文本文件

时间:2023-01-04 10:58:36浏览次数:36  
标签:Qt QFile 写入 文本文件 qDebug QIODevice txt open

打开文件时,使用参数选择打开文件模式

需要导入QFile和qDebug、QString头文件

写入

覆盖写入

1 QFile f("D:\\qtManager.txt");
2 if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
3 {
4     qDebug() << ("打开文件失败");
5 }
6 QTextStream txtOutput(&f);
7 QString str = "123";
8 txtOutput << str << endl;
9 f.close();

文末写入

1 QFile f("D:\\qtManager.txt");
2 if(!f.open(QIODevice::ReadWrite | QIODevice::Append))   //以读写且追加的方式写入文本
3 {
4     qDebug() << ("打开文件失败");
5 }
6 QTextStream txtOutput(&f);
7 QString str = "123";
8 txtOutput << str << endl;
9 f.close();

读取

 1 QFile f("D:\\qtManager.txt");
 2 if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
 3 {
 4     qDebug() << ("打开文件失败");
 5 }
 6 QTextStream txtInput(&f);                 
 7 QString lineStr;
 8 while(!txtInput.atEnd())
 9 {
10     lineStr = txtInput.readLine();
11     qDebug() << (lineStr);
12 }
13 f.close();

 

标签:Qt,QFile,写入,文本文件,qDebug,QIODevice,txt,open
From: https://www.cnblogs.com/ybqjymy/p/17024241.html

相关文章