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