Qt读写文件

1、头文件

#include<QFile>
#include<QFileDialog>  
#include<QDataStream>

2、写代码前工作

在ui界面拖入2个button按钮和1个textEdit,如下图所示,并分别添加button的槽函数

3、读文件

 1 void MyWidget::on_readButton_clicked()
 2 {
 3     QString path = QFileDialog::getOpenFileName(this,"open","../");  // 添加文件地址
 4     if(path.isEmpty() == false) // 判断地址是否不为空
 5     {
 6         QFile file(path);   // 创建文件接口
 7         bool success = file.open(QIODevice::ReadOnly);  // 判断文件打开方式是否设定成功
 8         if(success ==true)
 9         {
10             QByteArray buf;
11             while(file.atEnd() == false)    // 判断是否读取至最后一行
12             {
13                 buf += file.readLine(); // 读取内容
14             }
15             ui->textEdit->setText(buf); // 将读取到的内容放置textEdit中
16         }
17         file.close();   // 关闭文件接口
18     }
19 }
View Code

4、写文件

 1 void MyWidget::on_writeButton_clicked()
 2 {
 3     QString path = QFileDialog::getSaveFileName(this,"save","../"); // 默认打开地址
 4     if(path.isEmpty() == false) // 判断地址是否不为空
 5     {
 6         QFile file(path);   //打开文件接口
 7         bool success = file.open(QIODevice::WriteOnly); // 判断文件打开方式是否设定成功
 8         if(success == true)
 9         {
10             QString buf = ui->textEdit->toPlainText();  // 将textEdit中文本存入buf中
11             file.write(buf.toUtf8());   // 写入内容
12         }
13         file.close();   // 关闭文件接口
14     }
15 }
View Code

5、二进制文件写入

 1 void MyWidget::writeData()
 2 {
 3     QFile file("../binary.txt");    // 打开文件接口并设定存储方式为txt
 4     bool success = file.open(QIODevice::WriteOnly); // 判断文件打开方式是否设定成功
 5     if(success == true)
 6     {
 7         QDataStream stream(&file);  // 创建文件流
 8         stream<<QString("看多了就烦了 !")<<50; //写入
 9     }
10     file.close();   //关闭文件接口
11 }
View Code

6、二进制文件读取

 1 void MyWidget::readData()
 2 {
 3     QFile file("../binary.txt");    // 打开文件接口并设定打开路径
 4     bool success = file.open(QIODevice::ReadOnly);  // 判断文件打开方式是否设定成功
 5     if(success == true)
 6     {
 7         QDataStream stream(&file);  // 创建文件流
 8         QString str;
 9         int num;
10         stream>>str>>num;   // 读取
11         qDebug()<<str.toUtf8().data()<<num;
12     }
13     file.close();   // 关闭文件接口
14 }
View Code

猜你喜欢

转载自www.cnblogs.com/GEEK-ZHAO/p/12373504.html