QT读写文本文件和文件信息的获取

1、读文件

void RWfile::on_pb_r_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, "open", "../", "TEXT(*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file(path);
        if(file.open(QIODevice::ReadWrite))
        {
            //读文件默认只是识别utf8编码
            QByteArray by;
            //by = file.readAll();  //一次性读

            while(file.atEnd() == false)
            {
                by += file.readLine();  //按行读
            }
            ui->textEdit->setText(QString(by));
        }
        file.close();
    }
}

2、写文件

void RWfile::on_pb_w_clicked()
{
    QString path = QFileDialog::getSaveFileName(this, "save", "../", "text(*.txt)");
    if(path.isEmpty() == false)
    {
        QFile file(path);
        if(file.open(QIODevice::WriteOnly))
        {
            QString str = ui->textEdit->toPlainText();      //获取文本区内容

            //QString -> QByteArray
            //file.write(str.toUtf8());

            //根据编码格式
//            str.toUtf8();   //中文
//            str.toLocal8Bit();//本地编码

            //QString -> String -> char *
            file.write(str.toStdString().data());

            //QByteArray -> char *
//            QByteArray a = str.toUtf8();
//            char *b = a.data();

            //char * 转为 QString
//            QString c = QString(b);
        }

        file.close();
    }
}

3、文件信息的获取

QFileInfo info(path);
    qDebug() << "文件名称: " << info.baseName();
    qDebug() << "文件后缀: " << info.suffix();
    qDebug() << "文件大小: " << info.size();
    qDebug() << "文件创建时间: " << info.created().toString("yyyy-MM-dd hh:mm:ss");

你可能感兴趣的:(QT,qt)