QT之删除指定目录下指定尾缀文件

使用QT删除指定目录下指定尾缀的文件

use entryList

/*delete the files endswith ref 
dir_name: the dir to remove files
ref: the Suffix of files need to be removed
*/
void remove_files(QString& dir_name,QString& ref)
{
    if(dir_name.isEmpty() || ref.isEmpty())
        return;
    QDir dir(dir_name);
    //得到目录下的所有文件
    QStringList infolist = dir.entryList(QDir::Files,QDir::Time);
    //遍历获取的文件
    foreach(auto item,infolist )
    {
        if(item.endsWith(ref))
        {
            QFile::remove(dir_name+"/"+item);
        }
    }
}
 

use QFileInfoList entryInfoList

/*delete the files endswith ref 
dir_name: the dir to remove files
ref: the Suffix of files need to be removed
*/
void remove_files(QString& dir_name,QString& ref)
{
    if(dir_name.isEmpty() || ref.isEmpty())
        return;
    QDir dir(dir_name);
    //得到目录下的所有文件
    QFileInfoList infolist = dir.entryInfoList(QDir::Files,QDir::Time);
    //遍历获取的文件
    foreach(auto item,infolist )
    {
        if(item.fileName().endsWith(ref))
        {
            QFile::remove(item.absoluteFilePath());
        }
    }
}
 
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用QDir类和QFile类来实现查找指定目录下的指定文件是否存在。 首先,你需要创建一个QDir对象,指定要查找的目录路径。然后,你可以使用QDir::entryList()函数来获取目录下的所有文件和子目录。 接下来,遍历目录下的所有文件和子目录,如果是文件,使用QFile类的exists()函数来判断文件是否存在。如果是子目录,递归调用自己来查找子目录下的文件。 以下是示例代码: ```c++ #include <QCoreApplication> #include <QDir> #include <QFile> #include <QDebug> bool searchFile(const QString& path, const QString& fileName) { QDir dir(path); if(!dir.exists()){ qWarning() << "Path does not exist:" << path; return false; } dir.setFilter(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); QFileInfoList list = dir.entryInfoList(); foreach(QFileInfo fileInfo, list){ if(fileInfo.isDir()){ QString subDir = fileInfo.absoluteFilePath(); if(searchFile(subDir, fileName)){ return true; } }else{ QString file = fileInfo.fileName(); if(file == fileName){ qDebug() << "File found:" << fileInfo.absoluteFilePath(); return true; } } } return false; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QString path = "/path/to/search"; QString fileName = "file.txt"; if(searchFile(path, fileName)){ qDebug() << "File found!"; }else{ qDebug() << "File not found!"; } return a.exec(); } ``` 在上面的代码中,searchFile()函数用于查找指定目录下的指定文件。如果文件存在,函数返回true,否则返回false。函数中使用了递归来查找子目录下的文件。你可以将path和fileName替换为你要查找的目录和文件名。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值