首页 > 编程语言 >c++ 函数-遍历文件夹

c++ 函数-遍历文件夹

时间:2022-11-09 23:22:29浏览次数:40  
标签:遍历 string c++ filename 文件夹 path include ptr name

#pragma once

#include <iostream>
#include <string.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "dirent.h"
#include <time.h>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
#define MICRO_IN_SECOND 1000000
#define NANOS_IN_SECOND 1000000000

// 获取文件后缀名
static string getExtension(string filename) {
    return filename.substr(filename.find_last_of('.'));
}

// 判断是不是图片
static bool is_image(string filename) {
    string ext = getExtension(filename);
    vector<string> formats = {".jpg", ".jpeg", ".png", ".ppm", ".bmp", ".pgm", ".tif", ".tiff", ".webp"};
    vector<string>::iterator it = find(formats.begin(), formats.end(), ext);
    return it != formats.end();
}
// 获取文件名,不包含目录
static string getFilename(string file_fullpath) {
    return file_fullpath.substr(file_fullpath.find_last_of('/') + 1);
}
//获取文件名,不包含目录和后缀名
static string getFilenameNoExt(string filename) {
    filename = getFilename(filename);
    return filename.substr(0, filename.find_last_of('.'));
}
static string getParentPath(string file_fullpath) {
    int idx = file_fullpath.find_last_of('/');
    return file_fullpath.substr(0, idx);
}
//读取某给定路径下所有文件夹与文件名称,并带完整路径
static void getAllFilesInDirs(string path, vector<string> &fileFullpath) {
    DIR *pDir;
    struct dirent *ptr;
    if (!(pDir = opendir(path.c_str()))) return;
    while ((ptr = readdir(pDir)) != 0) {
        if (ptr->d_type == DT_DIR) {
            if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
                string new_path = path + "/" + ptr->d_name;
                getAllFilesInDirs(new_path, fileFullpath);
            }
        } else {
            fileFullpath.push_back(path + "/" + ptr->d_name);
        }
    }
    closedir(pDir);
}

//读取某给定路径下后缀名为format得文件名称,并带完整路径
static void getAllFilesByformat(string path, vector<string> &fileFullpath, string format) {
    DIR *pDir;
    struct dirent *ptr;
    string f;
    if (!(pDir = opendir(path.c_str()))) return;
    while ((ptr = readdir(pDir)) != 0) {
        if (ptr->d_type == DT_DIR) {
            if (strcmp(ptr->d_name, ".") != 0 && strcmp(ptr->d_name, "..") != 0) {
                string new_path = path + "/" + ptr->d_name;
                getAllFilesByformat(new_path, fileFullpath, format);
                }
        } else if (ptr->d_type == DT_REG && getExtension(ptr->d_name) == format) {
            f.clear();
            f = path + string("/") + string(ptr->d_name);
            fileFullpath.push_back(f);
        }
    }
    closedir(pDir);
}

 

标签:遍历,string,c++,filename,文件夹,path,include,ptr,name
From: https://www.cnblogs.com/dxscode/p/16196380.html

相关文章