zoukankan      html  css  js  c++  java
  • QFile文件读写

    • 参考代码

        .h文件

     1 #ifndef MYWIDGET_H
     2 #define MYWIDGET_H
     3 
     4 #include <QWidget>
     5 #include <QFile>
     6 #include <QFileDialog>
     7 namespace Ui {
     8 class myWidget;
     9 }
    10 
    11 class myWidget : public QWidget
    12 {
    13     Q_OBJECT
    14 
    15 public:
    16     explicit myWidget(QWidget *parent = 0);
    17     ~myWidget();
    18 
    19 private slots:
    20     void on_read_clicked();
    21 
    22     void on_write_clicked();
    23 
    24 private:
    25     Ui::myWidget *ui;
    26 };
    27 
    28 #endif // MYWIDGET_H

      .cpp文件

     1 #include "mywidget.h"
     2 #include "ui_mywidget.h"
     3 
     4 myWidget::myWidget(QWidget *parent) :
     5     QWidget(parent),
     6     ui(new Ui::myWidget)
     7 {
     8     ui->setupUi(this);
     9     setWindowTitle("QFile文件读写");
    10 }
    11 
    12 myWidget::~myWidget()
    13 {
    14     delete ui;
    15 }
    16 
    17 void myWidget::on_read_clicked()
    18 {
    19 QString path = QFileDialog::getOpenFileName(this,"open","../","TXT(*.txt)");
    20 if(path.isEmpty()==false)
    21 {
    22     QFile file(path);
    23     bool isOK = file.open(QIODevice::ReadOnly);
    24             if(isOK==true)
    25             {//方法1
    26 //                QByteArray array = file.readAll();
    27 //                ui->textEdit->setText(QByteArray(array));
    28 
    29                 QByteArray array;//方法2
    30                 while(file.atEnd()==false)
    31                 {
    32                     array += file.readLine();
    33                 }
    34                 ui->textEdit->setText(array);
    35             }
    36             file.close();
    37 
    38 }
    39 }
    40 
    41 void myWidget::on_write_clicked()
    42 {
    43     QString path = QFileDialog::getSaveFileName(this,"save","../","TXT(*.txt)");
    44     if(path.isEmpty()==false)
    45     {
    46         QFile file;
    47         file.setFileName(path);
    48         bool isOK = file.open(QIODevice::WriteOnly);
    49         if(isOK==true)
    50         {
    51           QString str = ui->textEdit->toPlainText();
    52           //file.write(str.toUtf8());
    53           file.write(str.toStdString().data());
    54         }
    55         file.close();
    56     }
    57 
    58 }
  • 相关阅读:
    Problem D: 双向冒泡排序
    Problem C: 查找最大元素
    Problem D: 小平查密码
    Problem C: 文件单词首字母大写
    Problem B: 文件操作文本文件读入
    Problem A: 文件操作二进制文件读入
    Problem A: 实现链表(线性表)
    【leetcode】包含min函数的栈
    【leetcode】反转链表
    【leetcode】合并两个排序的链表
  • 原文地址:https://www.cnblogs.com/fuzhuoxin/p/12170951.html
Copyright © 2011-2022 走看看