Qt - 使用QFile写文件
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 #include <QFile> 4 #include <QMessageBox> 5 #include <QTextStream> 6 7 MainWindow::MainWindow(QWidget *parent) : 8 QMainWindow(parent), 9 ui(new Ui::MainWindow) 10 { 11 ui->setupUi(this); 12 13 QString filename = "1.txt"; //当前文件夹中 14 QString str = "Qt QFile Test..."; //保存的文本内容 15 QFile file(filename); 16 if(!file.open(QIODevice::ReadWrite|QIODevice::Text)) 17 { 18 QMessageBox::warning(this,"file write","can't open",QMessageBox::Yes); 19 20 } 21 QTextStream in(&file); 22 in<<str<<"\n"; 23 24 } 25 26 MainWindow::~MainWindow() 27 { 28 file.close(); // 关闭file 29 delete ui; 30 }
在当前debug文件夹中会创建名为“1.txt”的文件