Qt5 文件读写

来源:互联网 发布:网络剧发行步骤 编辑:程序博客网 时间:2024/06/16 05:15

读写文件涉及到的几个类:<QTextStream> 和 <QFile>

读文件函数

  1. void ReadFile(const QString &filename)  
  2. {  
  3.     //QFile类提供读写文件的接口。QFile是一个用于读写文本文件和二进制文件和资源文件的I/O 设备  
  4.     QFile my_file(filename);//将QFile与相关文件关联  
  5.     if(!my_file.open(QIODevice::ReadOnly | QIODevice::Text))//以只读和文本模式打开文件  
  6.     {  
  7.         qDebug() <<"Could not open file for Reading";  
  8.         return;  
  9.     }  
  10.     //QTextStream提供一种读写文本文档边界的接口  
  11.     QTextStream outText(&my_file);  //将QTextStream与特定文件关联  
  12.     qDebug() << outText.readAll();  //读出QTextStream对象中所有内容  
  13.     my_file.close(); //关闭文件  
  14. }  

写文件函数

  1. void WriteFile(const QString &filename)  
  2. {  
  3.     QFile my_file(filename);  
  4.     if(!my_file.open(QIODevice::WriteOnly | QIODevice::Text))//以只写和文本模式打开文件  
  5.     {  
  6.         qDebug() <<"Could not open file for Writing";  
  7.         return;  
  8.     }  
  9.     QTextStream in(&my_file);  
  10.     in<<"Hello World!"//向QTextStream中写入内容  
  11.     my_file.flush();    //刷新文件,将buffer中所有数据写入文件,此语句不可少。  
  12.     my_file.close();  
  13. }  


0 0
原创粉丝点击