QT 文件夹操作

一丶文件夹

  1.创建文件夹
bool QDir::mkpath(const QString &dirPath) const
bool QDir::mkdir(const QString &dirName) const

重要的问题是mkpathmkdir的区别,如果需要创建一个父目录不存在的目录,就使用mkpath,否则会导致新建文件夹不成功,下面是(在当前应用程序目录下创建一个test文件夹)

QString curPath=QCoreApplication::applicationDirPath(); //获取应用程序所在文件夹的路径
示例
    QString str =  "/test";    
    QString path = QCoreApplication::applicationDirPath();
    QString test = path+str;   
    QDir *folder = new QDir;
    //判断创建文件夹是否存在
    bool exist = folder->exists(test);
    if(exist)
       {
             QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹已经存在!"));
       }
       else //如果不存在,创建文件夹
       {
             //创建文件夹
             bool ok = folder->mkpath(test);
             //判断是否成功
             if(ok)
             {
             QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹创建成功!"));
             }
             else
             {
             QMessageBox::warning(this,tr("创建文件夹"),tr("文件夹创建失败!"));
             }
        }
2.用户自己选择文件夹路径
QString dir_path=QFileDialog::getExistingDirectory(nullptr,"choose directory","C:/");
第一个参数是指定的父窗口
第二个参数是窗口的标题
第三个参数是初始从哪里开始查找
返回值为你选择的文件夹路径
3.获取文件夹下的子文件夹
QDir directory("D:/FastCharge"); // 替换为你的目录路径
        QStringList subDirectories;

        // 遍历所有子目录
        for(const QFileInfo& info : directory.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot)){
            if(info.isDir()){
                subDirectories.append(info.absoluteFilePath());
                qDebug() << "子目录名称:" << info.fileName(); // 获取子目录名称
            }
        }
        // 输出所有子目录路径
        for(const QString& subDir : subDirectories){
            qDebug() << subDir;
        }

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值