最近在做QT東西時遇到在指定路徑下創建文件,發現qt中沒有直接用的。
主要通過自定義一個createFile()函數來實現,其中需要用到<QFile> <QDir> <QDebug>頭文件。
為了測試方便,使用QDebug來進行信息點輸出。
1 void createFile(QString filePath,QString fileName) 2 { 3 QDir tempDir; 4 //臨時保存程序當前路徑 5 QString currentDir = tempDir.currentPath(); 6 //如果filePath路徑不存在,創建它 7 if(!tempDir.exists(filePath)) 8 { 9 qDebug()<<"不存在該路徑"<<endl; 10 tempDir.mkpath(filePath); 11 } 12 QFile *tempFile = new QFile; 13 //將程序的執行路徑設置到filePath下 14 tempDir.setCurrent(filePath); 15 qDebug()<<tempDir.currentPath(); 16 //檢查filePath路徑下是否存在文件fileName,如果停止操作。 17 if(tempFile->exists(fileName)) 18 { 19 qDebug()<<"文件存在"; 20 return ; 21 } 22 //此時,路徑下沒有fileName文件,使用下面代碼在當前路徑下創建文件 23 tempFile->setFileName(fileName); 24 if(!tempFile->open(QIODevice::WriteOnly|QIODevice::Text)) 25 { 26 qDebug()<<"打開失敗"; 27 } 28 tempFile->close(); 29 //將程序當前路徑設置為原來的路徑 30 tempDir.setCurrent(currentDir); 31 qDebug()<<tempDir.currentPath(); 32 }
實際使用時,可以根據需要將函數設置成bool類型,方便進行判斷是否創建成功。
