zoukankan      html  css  js  c++  java
  • 在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类型,方便进行判断是否创建成功。

  • 相关阅读:
    js操作
    函数知识点补充
    css---position
    css-浮动
    css-边界重叠以及边界塌陷
    css
    css文本类型操作
    POJ 2828 线段树活用
    POJ 3468 线段树
    POJ 3013 SPFA算法,邻接表的使用
  • 原文地址:https://www.cnblogs.com/zhangdewang/p/6838434.html
Copyright © 2011-2022 走看看