qt读写文本文件

使用QFile类进行读写,使用Open函数打开文件,打开方式有:

QIODevice::NotOpen 0x0000 不打开

QIODevice::ReadOnly 0x0001 只读方式

QIODevice::WriteOnly 0x0002 只写方式,如果文件不存在则会自动创建文件

QIODevice::ReadWrite ReadOnly | WriteOnly 读写方式

QIODevice::Append 0x0004 此模式表明所有数据写入到文件尾

QIODevice::Truncate 0x0008 打开文件之前,此文件被截断,原来文件的所有数据会丢失

QIODevice::Text 0x0010 读的时候,文件结束标志位会被转为’\n’;写的时候,文件结束标志位会被转为本地编码的结束为,例如win32的结束位’\r\n’

QIODevice::UnBuffered 0x0020 不缓存

第一种办法:QFile类的iodevice读写,即调用QIODevice类的函数

读:read、readall函数

写:write函数

#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
    //创建 QFile 对象,同时指定要操作的文件
    QFile file("D:/demo.txt");
    //对文件进行写操作
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
        qDebug()<<"文件打开失败";
    }
    //向文件中写入两行字符串
    file.write("C语言中文网\n");
    file.write("http://c.biancheng.net");
    //关闭文件
    file.close();

    //重新打开文件,对文件进行读操作
    if(!file.open(QIODevice::ReadOnly|QIODevice::Text)){
        qDebug()<<"文件打开失败";
    }
    //每次都去文件中的一行,然后输出读取到的字符串
    char * str = new char[100];
    qint64 readNum = file.readLine(str,100);
    //当读取出现错误(返回 -1)或者读取到的字符数为 0 时,结束读取
    while((readNum !=0) && (readNum != -1)){
        qDebug() << str;
        readNum = file.readLine(str,100);
    }
    file.close();
    return 0;
}

第二种办法:QFile + QTextStream 结合

读:readall、readline

写:<<

写文件

void writeTxt()
{
    // 文件位置
    QFile file("test.txt");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
    {
        return;
    }
    // 文件流
    QTextStream stream(&file);
    // 输入内容
    stream << "你好";
    stream << "111";
    file.close();
}
std::vector<QString> readTxt()
{
    // 返回值
    std::vector<QString> strs;
    // 读取文件位置
    QFile file("test.txt");
   
    if(!file.open(QIODevice::ReadOnly))
    {
        return strs;
    }
    // 文件流
    QTextStream stream(&file);
    // 一行一行的读
    while(!stream.atEnd())
    {
        QString line = stream.readLine();
        strs.push_back(line);
    }
    file.close();
    return strs;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值