linux获取子文件和子目录
#include <dirent.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <stdio.h>
// #include <android/log.h>
#define TAG "[demo]"
// #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__);
// #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__);
// #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__);
#define LOGD(...) fprintf(stdout, __VA_ARGS__);
#define LOGE(...) fprintf(stderr, __VA_ARGS__);
#define LOGI(...) fprintf(stdout, __VA_ARGS__);
// mode=1: 文件;mode=2: 目录
void getFileList(std::string dir_name, std::vector<std::string>& files, int mode){
if (dir_name.empty()) {
LOGE("%s", "dir_name is empty!");
return;
}
struct stat s;
stat(dir_name.c_str(), &s);
if(!S_ISDIR(s.st_mode)) {
LOGE("%s %s %s", "dir_name: ", dir_name.c_str(), " is not a valid directory!");
return;
}
struct dirent *filename;
DIR *dir;
dir = opendir(dir_name.c_str());
if(NULL == dir) {
LOGE("%s %s %s ", "Can not open dir: ", dir_name.c_str() ,"!");
return;
}
while ((filename = readdir(dir)) != NULL) {
if(strcmp(filename->d_name, ".") == 0 ||
strcmp(filename->d_name, "..") == 0)
continue;
// std::string filePath = dir_name + "/" + filename->d_name;
std::string filePath = filename->d_name;
if (((mode & 1) && is_file((dir_name + "/" + filePath).c_str()))
|| ((mode & 2) && is_dir((dir_name + "/" + filePath).c_str()))
|| (mode == 0)) {
files.push_back(filePath);
}
}
closedir(dir);
}
bool is_file(const char* filestr) {
struct stat buffer;
return (stat (filestr, &buffer) == 0 && S_ISREG(buffer.st_mode));
}
bool is_dir(const char* filestr) {
struct stat buffer;
return (stat (filestr, &buffer) == 0 && S_ISDIR(buffer.st_mode));
}
标签:__,VA,name,子目录,获取,mode,linux,dir,define
From: https://www.cnblogs.com/minding/p/17589410.html