其他分享
首页 > 其他分享> > qt中文件读取的方法(新手入门必看)

qt中文件读取的方法(新手入门必看)

作者:互联网

TxT文本文件读取

qt中三个常用的处理文件的头文件:
QDataStream
QTextStream
QFile

txt文件读取(以字符数组形式读取)

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QFile file(":/1/map.txt");//与文件建立联系
    if(!file.exists())//判断是否建立成功
    {

        QString str = "world";
        qDebug()<<"hello "<<str<<"!"<<endl;

    }
    else
    {
          this->showMaximized();//成功则窗口会最大化,这只是我用检测的方法
    }

if(file.open(QIODevice::ReadOnly|QIODevice::Text))//打开文件,以只读的方式打开文本文件
{
           qint32 n=file.readLine(*map,sizeof(map));//qint32 相当于c++中的int
           //因为readline函数读取文件内容成功的话就会返回文件的字节数,如果失败就会返回-1
           if(n!=-1){
               qDebug()<<"长度:"<<n
                      <<"内容:"<<map[2][2]
                     <<endl;
           }
           file.close();
       }
       else{
           qDebug()<<file.errorString();
           }
}

txt文件写入

   QFile file1("data1.txt");
    if(file1.open(QIODevice::WriteOnly|QIODevice::Truncate)){
        QDataStream out(&file1);
 
        out<<QString("周杰伦")
           <<QDate::fromString("1979-01-18","yyyy-MM-dd")//将日期格式化
        <<(qint32)41;
        file1.close();
 
    }else{
        qDebug()<<file1.errorString()<<endl;
    }

txt文件读取(第二种方式以数据流读取)

file1.setFileName("data1.txt");
    if(file1.open(QIODevice::ReadOnly)){
        //第二种方式就是一数据流读取文件内容
        QDataStream in(&file1);
        QString name;
        QDate birthday;
        qint32 age;
        in>>name>>birthday>>age;
        qDebug()<<name<<birthday<<age;
        file1.close();
 
    }else{
        qDebug()<<file1.errorString();
    }

参考博文

标签:文件,file1,qt,必看,新手入门,qDebug,QIODevice,txt,读取
来源: https://blog.csdn.net/qq_39838607/article/details/116354708