在QT中创建文件

最近在做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类型,方便进行判断是否创建成功。

posted @ 2017-05-10 22:14  在左手  阅读(32445)  评论(0编辑  收藏  举报