QT中读写文件操作

以下是notepad工程中的一些代码,用于打开和保存txt文件
首先需要包含以下头文件

#include 
#include 
#include 
#include 
#include 

1.打开文件

QString fileName = QFileDialog::getOpenFileName(this,"Open File",QDir::currentPath(),"Text File(*txt)");
if(fileName.isEmpty())
{
    QMessageBox::information(this,"Error","Please Choose File");
    return;
}

QFile *file = new QFile;
file->setFileName(fileName);
bool ok = file->open(QIODevice::ReadOnly);
if(ok)
{
    QTextStream in(file);
    ui->textEdit->setText(in.readAll());
    file->close();
    delete file;
}
else
{
    QMessageBox::information(this,"Error","Open File Error");
    return;
}

2.保存文件

QString fileName = QFileDialog::getSaveFileName(this,"Save File",QDir::currentPath,"Text File(*txt);;Jpg File(*.jpg)");
if(fileName.isEmpty())
{
    QMessageBox::information(this,"Error","FileName is NULL");
    return;
}

QFile *file = new QFile;
file->setFileName(fileName);
bool ok = file->open(QIODevice::WriteOnly);
if(ok)
{
    QTextStream out(file);
    out<<ui->textEdit->toPlainText();
    file->close();
    delete file;
}
else
{
    QMessageBox::information(this,"Error","Save File Error");
    return;
}

3.总结

qt中打开文件操作需要用到QFileDialog静态成员函数getOpenFileName函数来得到文件的绝对路径,如果选择取消则返回空字符串NULL。函数原型如下:

QString getOpenFileName(QWidget * parent = 0, //父窗体
         const QString & caption = QString(), //对话框标题
             const QString & dir = QString(), //打开的搜索路径
          const QString & filter = QString(), //文件过滤器,(;;)用双分号隔开
                 QString *selectedFilter = 0,
                         Options options = 0)

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