一、 Qt 中的读文本的内容
QTextStream
流读取文件中的内容,如读取每行的内容会自动去除行尾的换行符 \n
,而 QByteArray
会保存所有的字符,不会去除末尾的换行符。
1. 以 QTextStream
流的形式来读取文件中的内容。
#include <QFile>
#include <QTextStream>
#include <QDebug>
void ReadData(QString filePath)
{
QFile file(filePath);
if(!file.exists())
{
qDebug() << "can't find the file";
return;
}
if(!file.open(QIODevice::ReadOnly))
{
qDebug() << "can't open the file.";
return;
}
QTextStream stream(&file);
QString resStr = stream.readAll();
file.close();
}
void ReadData_M2(QString filePath)
{
QFile file(filePath);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "file open failed" << endl;
return;
}
QTextStream stream(&file);
while(!stream.atEnd())
{
QString line = file.readLine();
qDebug() << line << endl;
}
qDebug() << "Read all lines" << endl;
}
2. 向文件中写入数据
void WriteData(QString filePath)
{
QFile file(filePath);
if(!file.exists())
{
qDebug() << "can't find the file:" << filePath;
}
if(!file.open(QIODevice::ReadWrite | QIODevice::Text | QIODevice::Append))
{
qDebug() << "Open file error";
return;
}
QTextStream stream(&file);
QString str1 = "only for read test.";
QString str2 = "中文测试数据\n";
stream << str1 << str2;
file.flush();
file.close();
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器