使用Qt实现文本文件的读写操作

  #include "mainwindow.h"

  #include "ui_mainwindow.h"

  #include

  #include

  #include

  #include

  #include

  MainWindow::MainWindow(QWidget *parent)

  : QMainWindow(parent)

  , ui(new Ui::MainWindow)

  {

  ui->setupUi(this);

  connect(ui->openFileButton, &QPushButton::clicked, this, &MainWindow::openFile);

  connect(ui->saveFileButton, &QPushButton::clicked, this, &MainWindow::saveFile);

  }

  MainWindow::~MainWindow()

  {

  delete ui;

  }

  void MainWindow::openFile() {

  QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "",

  tr("Text Files (*.txt);;All Files (*)"));

  if (fileName.isEmpty()) {

  return;

  }

  QFile file(fileName);

  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {

  QMessageBox::warning(this, tr("Error"), tr("Cannot open file for reading"));

  return;

  }

  QTextStream in(&file);

  currentFileContent = in.readAll();

  file.close();

  QMessageBox::information(this, tr("Success"), tr("File content read successfully"));

  qDebug() << currentFileContent;

  }

  void MainWindow::saveFile() {

  QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), "",

  tr("Text Files (*.txt);;All Files (*)"));

  if (fileName.isEmpty()) {

  return;

  }

  QFile file(fileName);

  if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {

  QMessageBox::warning(this, tr("Error"), tr("Cannot open file for writing"));

  return;

  }

  QTextStream out(&file);

  out << currentFileContent;

  file.close();

  QMessageBox::information(this, tr("Success"), tr("File saved successfully"));

  }