Qt文件读写的天花板QFile和IODevice搭配第一集
想看更多精彩内容内容,锁定:
文件读写共计3集,想看全集记得去Qt专栏
一、QFile读写文本文件
文件打开的方式:
【1】QIODevice::ReadOnly ->只读打开
【2】QIODevice::WriteOnly ->只写打开
【3】QIODevice::ReadWrite ->读写打开
【4】QIODevice::Append ->追加打开(尾追),配合以上几种,用 | 隔开 可以称为管道或 者按位或
【5】QIODevice::Truncate ->清空打开,每次打开文件,原有内容清空
【6】QIODevice::Text ->文本打开方式,读取时”\n”被自动翻译为换行符,写入时字符串 结束符会自动翻译为系统平台的编码,如Windows是\r\n Linux平台\n
注意:只有WriteOnly时,隐含是Truncate模式,删除文件原有内容,还有一点,以上 这些打开文件,如果文件不存在,就创建文件,文件名必须给定。
二.QFile和IODevice举例
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>//文件读写
#include<QDir>//目录
#include<QTextStream>//文件流
#include<QFileDialog>//文件对话框
#include<QDebug>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
//打开文件
void MainWindow::on_openfile_clicked()
{
QString curPath =QDir::currentPath();//获取当前路径
qDebug()<<"curPath="<<curPath<<endl;//默认编译路径
QString openTitle ="打开一个文件";
QString filter ="程序文件(*.h *.cpp);;文本文件(*.txt);;所有文件(*.*)";//文件过滤器
QString FilePath = QFileDialog::getOpenFileName(this,openTitle,curPath,filter);
qDebug()<<"FilePath="<<FilePath<<endl;
if(FilePath.isEmpty()){
return;
}
myCreatePublicOpenTextByIODevice(FilePath);
}
//文件读写采用IODevice方式
bool MainWindow::myCreatePublicOpenTextByIODevice(const QString &FilenamePath)
{
QFile file(FilenamePath);
if(!file.exists())//文件不存在
{
qDebug()<<file.errorString()<<endl;
return false;
}
//打开文件:只读,识别\n符
if(!file.open(QIODevice::ReadOnly|QIODevice::Text))
return false;//文件打开失败
//追加方式显示
//ui->plainTextEdit->appendPlainText(file.readAll());//一次性读完
//每次读取有一行
qDebug()<<"filename="<<file.fileName()<<endl;
while(!file.atEnd())
{
ui->plainTextEdit->appendPlainText(file.readLine());
}
file.close();//关闭文件
return true;
}
//文件另存
void MainWindow::on_filesave_clicked()
{
QString curPath =QDir::currentPath();//获取当前路径
qDebug()<<"curPath="<<curPath<<endl;//默认编译路径
QString openTitle ="另存文件";
QString filter ="程序文件(*.h *.cpp);;文本文件(*.txt);;所有文件(*.*)";//文件过滤器
QString FilePath = QFileDialog::getOpenFileName(this,openTitle,curPath,filter);
qDebug()<<"FilePath="<<FilePath<<endl;
if(FilePath.isEmpty()){
return;
}
myCreatePublicSaveFile(FilePath);
}
bool MainWindow::myCreatePublicSaveFile(const QString &FilenamePath)
{
QFile file(FilenamePath);
if(!file.exists())//文件不存在
{
qDebug()<<file.errorString()<<endl;
return false;
}
//打开文件:只读,识别\n符
if(!file.open(QIODevice::WriteOnly|QIODevice::Text))
return false;//文件打开失败
QString getText = ui->plainTextEdit->toPlainText();//获取整个内容
QByteArray textBytes = getText.toUtf8();//转为字节数组
file.write(textBytes,textBytes.size());
//file.write(textBytes,textBytes.length());//与上述一样
qDebug()<<"textBytes.size("<<textBytes.size()<<"textBytes.length()"
<<textBytes.length()<<endl;
file.close();//关闭文件
return true;
}
打开stm文件,并写入内容
打开文件,读取内容,显示在文本框
记得锁定专栏,一直更新哦