qt4 读写text

read
#include<QMessageBox>
#include<QFile>
#include<QFileDialog>
#include<QTextStream>

void MainWindow::on_pushButton_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this);//使用对话框选择路径及文件名
  //QString fileName="/opt/i_am_file.txt";//绝对路径
  //QString fileName="i_am_file.txt";//相对路径,当前目录下的i_am_file.txt

    if(!fileName.isEmpty())//如果文件名不为空
    {
        QFile file(fileName);
        if(!file.open(QFile::ReadOnly | QFile::Text))
        {
        QMessageBox::warning(this,tr("读取文件"),tr("无法读取文件 %1:\n%2.").arg(fileName).arg(file.errorString()));
        return ; //如果打开文件失败,弹出对话框,并返回
        }
        QTextStream in(&file);
        QString str=in.readAll();
        QMessageBox box;
        box.setText(str);
        box.exec();
    }
}

write
void MainWindow::on_pushButton_2_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this,tr("另存为"),"i_am_file.txt");//使用对话框选择路径及文件名
    //QString fileName="i_am_file.txt";

    if(!fileName.isEmpty())//如果文件名不为空
    {   QFile file(fileName);
        if(!file.open(QFile::WriteOnly | QFile::Text))
        //以只写方式打开文件,如果打开失败则弹出提示框并返回
        {
        QMessageBox::warning(this,tr("保存文件"),tr("无法保存文件 %1:\n %2").arg(fileName).arg(file.errorString()));
        return ;
        }
        //%1,%2表示后面的两个arg参数的值
        QTextStream out(&file); //新建流对象,指向选定的文件
        //out << ui->textEdit->toPlainText(); //将文本编辑器里的内容以纯文本的形式输出到流对象中
        out<<"hello evryone";

        QString curFile = QFileInfo(fileName).canonicalFilePath(); //获得文件的标准路径
        QMessageBox box;
        box.setText(curFile);
        box.exec();
      }
    return ;
}

http://www.yafeilinux.com/?p=37


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值