Qt檔案讀寫操作
file.write("hello Qt");
file.close();
以讀的方式開啟
if(file.open(QIODevice::ReadOnly))
{
QString str = file.readAll();
qDebug() << str;
}
當然也有其它兩種方式來實現讀/寫檔案
1.使用文字流讀寫文字檔案
QFile file("myFile.txt);
if(file.open(QIODevice::WriteOnly))
{
QTextStream out(&file);
out << "Hello Qt" << 123;
}
if(file.open(QIODevice::ReadOnly))
{
QTextStream in(&file);
while(in.atEnd())
{
QString str;
str = in.readLine();
qDebug() << str;
}
}
2.使用資料流來讀寫二進位制檔案
QFile file("myFile.txt");
if(file.open(QIODevice::WriteOnly))
{
QDataStream out(&file);
out << QString("hello Qt") << 123; //以二進位制形式儲存,開啟是亂碼,必須使用下面的方法進行記取
}
if(file.open(QIODevice::ReadOnly))
{
QDataStream in(&file);
QString str;
in >> str;
qDebug() << str;
}
同樣也可以對檔案進行監聽,當檔案或資料夾改變時發生相應的變化
建構函式中寫:
myWatcher = new QFileSystemWatcher;
connect(myWatcher,SIGNAL(fileChanged(QString)),this,SLOT(showMessage(QString)));
connect(myWatcher,SIGNAL(directoryChanged(QString)),this,SLOT(showMessage(QString)));
QDir myDir(QDir::currentPath());
ui->listWidget->addItem(myDir.absolutePath()+"當前路徑");
myDir.setNameFilters(QStringList("*.h"));
ui->listWidget->addItems(myDir.entryList());
myDir.mkdir("myDir");
myDir.cd("myDir");
ui->listWidget->addItem("監視的目錄"+myDir.absolutePath());
myWatcher->addPath(myDir.absolutePath());
QFile file(myDir.absolutePath()+"/myFile.txt");
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
qDebug() << file.errorString();
file.write("hello! QT");
QFileInfo fileInfo(file);
ui->listWidget->addItem("監視的檔案"+fileInfo.absoluteFilePath());
myWatcher->addPath(fileInfo.absoluteFilePath());
file.close();
QFile data("data.txt");
if(data.open(QFile::WriteOnly | QFile::Text))
{
QDataStream out(&data);
out << QString("dd");
out << qint32(11);
}
data.close();
if(data.open(QFile::ReadOnly | QFile::Text))
{
QDataStream in(&data);
QString str1;
qint32 str2;
in >> str1 >> str2;
qDebug() <<str1 << str2;
}
}
void MainWindow::showMessage(const QString &path)
{
QDir dir(QDir::currentPath()+"/myDir");
if(path == dir.absolutePath())
{
qDebug() << "目錄"+path+"變化";
}else
{
qDebug() << "檔案"+path+"變化";
}
}