一、就是我們自己的項目下有一個data.txt的文件和Data的文件夾裏面有一個datastream.txt的文件,我分別想直接讀取裏面的文件
1、需要加上頭文件如下:
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
2、讀取data.txt文件如下,直接跟mainwindow放在同一層目錄:
QString filename ="data.txt";
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream txtInput(&file);
txtInput.setCodec("UTF-8");
QString str ;
while (!txtInput.atEnd())
{
str = txtInput.readLine();
}
qDebug()<<"str ="<<str;
2、直接在mainwindow的同級目錄下新建一個文件夾Data,然後裏面放上datastream.txt文件,操作如下:
//第二種做法,比較安全點
QString path = QDir::currentPath();
QString filename =path+"/Data/datastream.txt";
QFile file(filename);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream txtInput(&file);
txtInput.setCodec("UTF-8");
QString str ;
while (!txtInput.atEnd())
{
str = txtInput.readLine();
}
qDebug()<<"str ="<<str;