一、UI界面
二、源文件代码
1、第一种方式
#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QDebug>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_btnreadFile_clicked() //读取文件
{
//1. 打开文件
//QFile file("D:/QT project/onetext.txt");
QFile file;
file.setFileName("D:/QT project/onetext.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "file open error";
}
//2. 读取文件
char context[100] = {'\0'};
if( file.read(context,100) == -1) return;
//3. 输出文件内容
qDebug() << context;
file.close();
}
void Widget::on_btnwriteFile_clicked() // 写入文件
{
// 1.打开
QFile file("D:/QT project/onetext.txt");
file.open(QIODevice::WriteOnly | QIODevice::Text);
// 2. 写入
file.write("Program 45-QFile001 write something to This File");
// 3. 关闭
file.close();
}
2、第二种方式
void Widget::on_btnreadFile_clicked() //读文件
{
QFile file;
file.setFileName("D:/QT project/onetext.txt");
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
qDebug() << "file open error";
}
QTextStream in(&file);
in.setCodec("UTF-8");
// QString context = in.read(file.size());
while(!in.atEnd()){
QString context = in.readLine();
qDebug() << context;
}
file.close();
}
void Widget::on_btnwriteFile_clicked() //写文件
{
QFile file;
file.setFileName("D:/QT project/onetext.txt");
if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){
qDebug() << "file open error";
}
QTextStream out(&file);
out.setCodec("UTF-8");
out << "I write stream char to File";
file.close();
}