Qt---读写文件

在程序的开发过程中,经常会需要进行文件的读写,Qt提供了两种读写文本文件的方法:

1、使用QFile 类的 IODevice 读写功能

2 、QFile 和 QTextStream 结合

 

使用QFile 类的 IODevice 读写

1)读文件

 

 1 bool widget::readFile(const QString &fileName)
 2 {
 3     //打开文件
 4     QFile   file(fileName);
 5     if (!file.exists()) //文件不存在
 6         return false;
 7 
 8     if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
 9         return false;
10 
11     //读取所有文本
12     QString allText = file.readAll();
13 
14     //读取一行
15     QString lineText = file.readLine();
16 
17     file.close();
18     return true;
19 }

 

调用QFile的open()函数打开文件时,需要传递QIODevice::OpenModeFlag枚举类型的参数,其决定着文件以什么样的方式打开,QIODevice::OpenModeFlag类型的主要取值如下:

  • QIODevice::ReadOnly:以只读方式打开文件,用于载入文件。
  • QIODevice::WriteOnly:以只写方式打开文件,用于保存文件。
  • QIODevice::ReadWrite:以读写方式打开。
  • QIODevice::Append:以添加模式打开,新写入文件的数据添加到文件尾部。
  • QIODevice::Truncate:以截取方式打开文件,文件原有的内容全部被删除。
  • QIODevice::Text:以文本方式打开文件,读取时“\n”被自动翻译为换行符,写入时字符串结束符会自动翻译为系统平台的编码,如 Windows 平台下是“\r\n”。

 

2)写文件

 1 bool Widget::wirteFile(const QString &fileName)
 2 {
 3     //打开文件
 4     QFile file(fileName);
 5     if (!file.open(QIODevice::WriteOnly | QIODevice::Text))//以只写方式打开
 6         return false;
 7 
 8     QString str = "Hello Qt!";
 9     QByteArray  strBytes = str.toUtf8();//转换为字节数组
10 
11     //写入文件
12     file.write(strBytes, strBytes.length());
13 
14     //关闭文件
15     file.close();
16     return true;
17 }

 

QFile 和 QTextStream 结合

1)读文件

 1 bool Widget::readFileByStream(const QString &fileName)
 2 {
 3     //打开文件
 4     QFile file(fileName);
 5 
 6     //判断文件是否存在
 7     if (!file.exists())
 8     {
 9         return false;
10     }
11 
12     if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
13     {
14         return false;
15     }
16 
17     //创建QTextStream对象
18     QTextStream textStream(&file);
19 
20     //读取一行
21     QString lineData = textStream.readLine();   //读取文件的第一行
22     lineData = textStream.readLine();           //此时读的是文件的第二行
23 
24     //读取全部内容
25     QString allData = textStream.readAll();
26 
27     //关闭文件
28     file.close();
29     return true;
30 }

 

2)写文件

 1 bool Widget::wirteFileByStream(const QString &fileName)
 2 {
 3     //打开文件
 4     QFile file(fileName);
 5     if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
 6     {
 7         return false;
 8     }
 9 
10     //用文本流写入文件
11     QTextStream textStream(&file);
12 
13     //写入文本流
14     QString str = "Hello Qt!";
15     textStream << str;//必要时加上换行符"\n"
16 
17     //关闭文件
18     file.close();
19     return true;
20 }

 

posted on 2021-05-26 22:12  深蓝火焰  阅读(724)  评论(0)    收藏  举报