// example intfileNameFilter(const struct dirent *cur){ std::string str(cur->d_name); if (str.find(".png") != std::string::npos) { return1; } return0; }
voiddeleteNFiles(const std::string &vDir, constint vNum){ if (vDir.empty()) { return; } int num = vNum; structstats; lstat(vDir.c_str(), &s); if (!S_ISDIR(s.st_mode)) { // LOG_WARN("{} is not a valid directory.", vDir); return; }
structdirent **files; int count; count = scandir(vDir.c_str(), &files, fileNameFilter, alphasort);
for (int i = 0; i < count && num > 0; ++i) { // char szChild[256] = {0}; // sprintf(szChild, "%s/%s", vDir, files[i]->d_name); std::string path = vDir + "/"; path.append(std::string(files[i]->d_name)); if (files[i]->d_type != 0x08) { continue; } lstat(path.c_str(), &s); if (0 == remove(path.c_str())) { num--; } } free(files); }
voiddeleteNFiles(const std::string &vDir, constint vNum){ if (vDir.empty()) { return; } int num = vNum; structstats; lstat(vDir.c_str(), &s); if (!S_ISDIR(s.st_mode)) { // LOG_WARN("{} is not a valid directory.", vDir); return; }
DIR *pDir = opendir(vDir.c_str()); if (nullptr == pDir) { return; } structdirent *filename; while ((filename = readdir(pDir)) != nullptr && num > 0) { LOG_INFO("file: {}", filename->d_name); if (strcmp(filename->d_name, ".") == 0 || strcmp(filename->d_name, "..") == 0) { continue; } char szChild[256] = {0}; sprintf(szChild, "%s/%s", vDir.c_str(), filename->d_name); if (filename->d_type != 0x8) { // not file continue; } lstat(szChild, &s); if (0 == remove(szChild)) { num--; } } }
structdirent *filename; DIR *file_dir; file_dir = opendir(dir.c_str()); if (nullptr == file_dir) { return files; }
/* read all the files in the dir ~ */ while ((filename = readdir(file_dir)) != nullptr) { // get rid of "." and ".." if (strcmp(filename->d_name, ".") == 0 || strcmp(filename->d_name, "..") == 0 || filename->d_type == 4) continue; files.push_back(filename->d_name); }