static int psy_enum_devs(void) { #ifdef WIN32 int fd, i, ret = 0; char name[MAX_FNAME_SZ]; for (i = 0; i < MAX_PSY_DEVS; i++) { snprintf(name, MAX_FNAME_SZ, "/dev/power_supply%d", i); fd = open(name, O_RDWR); if (fd < 0) continue; ret = psy_add_dev(fd); if (ret) { close(fd); break; } } return ret; #else DIR *dir; struct dirent *entry = NULL; dir = opendir("/sys/class/power_supply"); if (dir == NULL) return errno; for (entry = readdir(dir); entry != NULL;) { if (entry->d_name[0] != '.') { if (psy_add_dev(entry->d_name)) { closedir(dir); return errno; } } if (readdir_r(dir, entry, &entry)) { closedir(dir); return errno; } } closedir(dir); return 0; #endif }
int VolumeManager::unmountAllAsecsInDir(const char *directory) { DIR *d = opendir(directory); int rc = 0; if (!d) { SLOGE("Could not open asec dir %s", directory); return -1; } size_t dirent_len = offsetof(struct dirent, d_name) + fpathconf(dirfd(d), _PC_NAME_MAX) + 1; struct dirent *dent = (struct dirent *) malloc(dirent_len); if (dent == NULL) { SLOGE("Failed to allocate memory for asec dir"); return -1; } struct dirent *result; while (!readdir_r(d, dent, &result) && result != NULL) { if (dent->d_name[0] == '.') continue; if (dent->d_type != DT_REG) continue; size_t name_len = strlen(dent->d_name); if (name_len > 5 && name_len < (ID_BUF_LEN + ASEC_SUFFIX_LEN - 1) && !strcmp(&dent->d_name[name_len - 5], ASEC_SUFFIX)) { char id[ID_BUF_LEN]; strlcpy(id, dent->d_name, name_len - 4); if (unmountAsec(id, true)) { /* Register the error, but try to unmount more asecs */ rc = -1; } } } closedir(d); free(dent); return rc; }
bool listsubdir(const char *dir, vector<char *> &subdirs) { #if defined(WIN32) defformatstring(pathname)("%s\\*", dir); WIN32_FIND_DATA FindFileData; HANDLE Find = FindFirstFile(path(pathname), &FindFileData); if(Find != INVALID_HANDLE_VALUE) { do { if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && FindFileData.cFileName[0] != '.') subdirs.add(newstring(FindFileData.cFileName)); } while(FindNextFile(Find, &FindFileData)); FindClose(Find); return true; } #else string pathname; copystring(pathname, dir); DIR *d = opendir(path(pathname)); if(d) { struct dirent *de, b; while(!readdir_r(d, &b, &de) && de != NULL) { #ifdef _DIRENT_HAVE_D_TYPE if(de->d_type == DT_DIR && de->d_name[0] != '.') subdirs.add(newstring(de->d_name)); else if(de->d_type == DT_UNKNOWN && de->d_name[0] != '.') #endif { struct stat s; int dl = (int)strlen(pathname); concatformatstring(pathname, "/%s", de->d_name); if(!lstat(pathname, &s) && S_ISDIR(s.st_mode) && de->d_name[0] != '.') subdirs.add(newstring(de->d_name)); pathname[dl] = '\0'; } } closedir(d); return true; } #endif else return false; }
void scandir(const std::string& path, const std::string& extension, std::vector<std::string>* files) { files->clear(); std::string search_path = path.empty() ? "." : path; DIR* dir = opendir(ResolvePath(search_path).c_str()); if (!dir) return; struct dirent entry; struct dirent* result; while (readdir_r(dir, &entry, &result) == 0) { if (result == NULL) break; if (mats::ends_with(entry.d_name, extension)) { files->emplace_back(entry.d_name); } } closedir(dir); }
static void synthesize_all(void) { DIR *proc; struct dirent dirent, *next; proc = opendir("/proc"); while (!readdir_r(proc, &dirent, &next) && next) { char *end; pid_t pid, tgid; pid = strtol(dirent.d_name, &end, 10); if (*end) /* only interested in proper numerical dirents */ continue; tgid = pid_synthesize_comm_event(pid, 1); pid_synthesize_mmap_samples(pid, tgid); } closedir(proc); }
static int local_readdir_r(FsContext *ctx, V9fsFidOpenState *fs, struct dirent *entry, struct dirent **result) { int ret; again: ret = readdir_r(fs->dir, entry, result); if (ctx->export_flags & V9FS_SM_MAPPED) { entry->d_type = DT_UNKNOWN; } else if (ctx->export_flags & V9FS_SM_MAPPED_FILE) { if (!ret && *result != NULL && !strcmp(entry->d_name, VIRTFS_META_DIR)) { /* skp the meta data directory */ goto again; } entry->d_type = DT_UNKNOWN; } return ret; }
void CommandListener::AsecCmd::listAsecsInDirectory(SocketClient *cli, const char *directory) { DIR *d = opendir(directory); if (!d) { cli->sendMsg(ResponseCode::OperationFailed, "Failed to open asec dir", true); return; } size_t dirent_len = offsetof(struct dirent, d_name) + fpathconf(dirfd(d), _PC_NAME_MAX) + 1; struct dirent *dent = (struct dirent *) malloc(dirent_len); if (dent == NULL) { cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", true); return; } struct dirent *result; while (!readdir_r(d, dent, &result) && result != NULL) { if (dent->d_name[0] == '.') continue; // For whatever reason, the exFAT fuse driver reports DT_UNKNOWN for // the .asec files, so we'll have to allow that to make external apps // work properly. if (dent->d_type != DT_REG && dent->d_type != DT_UNKNOWN) continue; size_t name_len = strlen(dent->d_name); if (name_len > 5 && name_len < 260 && !strcmp(&dent->d_name[name_len - 5], ".asec")) { char id[255]; memset(id, 0, sizeof(id)); strlcpy(id, dent->d_name, name_len - 4); cli->sendMsg(ResponseCode::AsecListResult, id, false); } } closedir(d); free(dent); }
void removeDirectory(const Path &path) { DIR *d = opendir(path.constData()); size_t path_len = path.size(); char buf[PATH_MAX]; dirent *dbuf = reinterpret_cast<dirent*>(buf); if (d) { dirent *p; while (!readdir_r(d, dbuf, &p) && p) { char *buf; size_t len; /* Skip the names "." and ".." as we don't want to recurse on them. */ if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, "..")) { continue; } len = path_len + strlen(p->d_name) + 2; buf = static_cast<char*>(malloc(len)); if (buf) { struct stat statbuf; snprintf(buf, len, "%s/%s", path.constData(), p->d_name); if (!stat(buf, &statbuf)) { if (S_ISDIR(statbuf.st_mode)) { removeDirectory(buf); } else { unlink(buf); } } free(buf); } } closedir(d); } rmdir(path.constData()); }
// Create directory and copy contents (does not overwrite existing files) void CopyDir(const std::string &source_path, const std::string &dest_path) { #ifndef _WIN32 if (source_path == dest_path) return; if (!File::Exists(source_path)) return; if (!File::Exists(dest_path)) File::CreateFullPath(dest_path); struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; struct dirent_large diren; struct dirent *result = NULL; DIR *dirp = opendir(source_path.c_str()); if (!dirp) return; while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) continue; std::string source, dest; source = source_path + virtualName; dest = dest_path + virtualName; if (IsDirectory(source)) { source += '/'; dest += '/'; if (!File::Exists(dest)) File::CreateFullPath(dest); CopyDir(source, dest); } else if (!File::Exists(dest)) File::Copy(source, dest); } closedir(dirp); #endif }
static void /* List all files in directory 'dirpath' */ listFiles(const char *dirpath) { DIR *dirp; struct dirent entry, *result; Boolean isCurrent; /* True if 'dirpath' is "." */ isCurrent = strcmp(dirpath, ".") == 0; dirp = opendir(dirpath); if (dirp == NULL) { errMsg("opendir failed on '%s'", dirpath); return; } /* For each entry in this directory, print directory + filename */ for (;;) { errno = 0; /* To distinguish error from end-of-directory */ if (readdir_r(dirp, &entry, &result) == -1) { errMsg("readdir_r"); continue; } if (result == NULL) break; if (strcmp(entry.d_name, ".") == 0 || strcmp(entry.d_name, "..") == 0) continue; /* Skip . and .. */ if (!isCurrent) printf("%s/", dirpath); printf("%s\n", entry.d_name); } if (errno != 0) errExit("readdir"); if (closedir(dirp) == -1) errMsg("closedir"); }
int perf_event__synthesize_threads(perf_event__handler_t process, struct perf_session *session) { DIR *proc; struct dirent dirent, *next; union perf_event *comm_event, *mmap_event; int err = -1; comm_event = malloc(sizeof(comm_event->comm) + session->id_hdr_size); if (comm_event == NULL) goto out; mmap_event = malloc(sizeof(mmap_event->mmap) + session->id_hdr_size); if (mmap_event == NULL) goto out_free_comm; proc = opendir("/proc"); if (proc == NULL) goto out_free_mmap; while (!readdir_r(proc, &dirent, &next) && next) { char *end; pid_t pid = strtol(dirent.d_name, &end, 10); if (*end) /* only interested in proper numerical dirents */ continue; __event__synthesize_thread(comm_event, mmap_event, pid, process, session); } closedir(proc); err = 0; out_free_mmap: free(mmap_event); out_free_comm: free(comm_event); out: return err; }
value arc_dir(arc *c, value dirname) { char *utf_filename; DIR *dirp; int en; value dirlist; struct dirent *entry, *result; int delen; TYPECHECK(dirname, T_STRING); utf_filename = alloca(FIX2INT(arc_strutflen(c, dirname)) + 1); arc_str2cstr(c, dirname, utf_filename); dirp = opendir(utf_filename); if (dirp == NULL) { en = errno; arc_err_cstrfmt(c, "dir: cannot open directory \"%s\", (%s; errno=%d)", utf_filename, strerror(en), en); return(CNIL); } dirlist = CNIL; delen = offsetof(struct dirent, d_name) + pathconf(utf_filename, _PC_NAME_MAX) + 1; entry = (struct dirent *)alloca(delen); for (;;) { if (readdir_r(dirp, entry, &result) != 0) { /* error */ en = errno; arc_err_cstrfmt(c, "dir: error reading directory \"%s\", (%s; errno=%d)", utf_filename, strerror(en), en); return(CNIL); } /* end of list */ if (result == NULL) break; /* ignore the . and .. directories */ if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; dirlist = cons(c, arc_mkstringc(c, entry->d_name), dirlist); } closedir(dirp); return(dirlist); }
ssize_t native_dir::read_all_files(std::vector<std::string> &files) const { DIR *d = opendir(name.c_str()); if (d == NULL) { fprintf(stderr, "can't open %s: %s\n", name.c_str(), strerror(errno)); return -1; } struct dirent *entryp; long path_limit = pathconf(name.c_str(), _PC_NAME_MAX); if (path_limit < 0) { perror("pathconf"); path_limit = sizeof(entryp->d_name); } int len = offsetof(struct dirent, d_name) + path_limit + 1; entryp = (struct dirent *) malloc(len); struct dirent *result; ssize_t num = 0; while (true) { int ret = readdir_r(d, entryp, &result); if (ret != 0) { fprintf(stderr, "can't read dir %s: %s\n", name.c_str(), strerror(ret)); num = -1; break; } // End of the directory stream. if (result == NULL) break; assert(result == entryp); std::string file = entryp->d_name; if (file != "." && file != "..") files.push_back(file); num++; } free(entryp); closedir(d); return num; }
int32_t ReadDirR(DIR* dir, void* buffer, int32_t bufferSize, DirectoryEntry* outputEntry) { assert(buffer != nullptr); assert(dir != nullptr); assert(outputEntry != nullptr); if (bufferSize < sizeof(dirent)) { assert(!"Buffer size too small; use GetDirentSize to get required buffer size"); return ERANGE; } // On successful cal to readdir_r, result and &entry should point to the same // data; a NULL temp pointer but return of 0 means that we reached the end of the // directory stream; finally, a NULL temp pointer with a positive return value // means an error occurred. dirent* result = nullptr; dirent* entry = (dirent*)buffer; int ret = readdir_r(dir, entry, &result); if (ret == 0) { if (result != nullptr) { assert(result == entry); ConvertDirent(*entry, outputEntry); } else { ret = -1; // errno values are positive so signal the end-of-stream with a non-error value *outputEntry = { }; } } else { *outputEntry = { }; } return ret; }
inline Try<std::list<std::string>> ls(const std::string& directory) { DIR* dir = opendir(directory.c_str()); if (dir == nullptr) { // Preserve `opendir` error. return ErrnoError("Failed to opendir '" + directory + "'"); } dirent* temp = (dirent*) malloc(os::dirent_size(dir)); if (temp == nullptr) { // Preserve `malloc` error. ErrnoError error("Failed to allocate directory entries"); closedir(dir); return error; } std::list<std::string> result; struct dirent* entry; int error; while ((error = readdir_r(dir, temp, &entry)) == 0 && entry != nullptr) { if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } result.push_back(entry->d_name); } free(temp); closedir(dir); if (error != 0) { // Preserve `readdir_r` error. return ErrnoError("Failed to read directories"); } return result; }
bool Motor::connect(enum MotorPort port) { DIR *dir = opendir(motorRootPath); struct dirent dent; struct dirent *dptr; unsigned long n; const size_t pathSize = MOTORPATHNAME_MAX; char path[pathSize]; const size_t bufferSize = 5; char buffer[bufferSize]; if (dir == nullptr) return false; do { if (readdir_r(dir, &dent, &dptr) != 0 || dptr == 0) goto failed; /* We disregard all directories that start with a . */ if (dent.d_name[0] == '.') continue; snprintf(path, pathSize, "%s/%s/port_name", motorRootPath, dent.d_name); memset(buffer, 0, bufferSize); n = readfile(path, buffer, bufferSize); /* We only care about the first 4 chars, if they are contain * the correct magic out[ABCD] */ if (n >= 4 && strncmp(buffer, portNames[port], 4) == 0) break; } while(true); snprintf(motorPath, sizeof(motorPath), "%s/%s", motorRootPath, dent.d_name); closedir(dir); setupFastPaths(dent.d_name); scanParams(); return paramsOK; failed: closedir(dir); return false; }
int Storage::cleanSubDir(const char *dir) { static bool reportedError=false; //avoid filling up syslog DIR *d=opendir(dir); bool hadError=false; int bytesDeleted=0; if (d) { struct dirent *txtfile, path; struct stat txtfilestat; char fullPath[PATH_MAX]; int filesize; while ( (!readdir_r(d, &path, &txtfile) && txtfile != NULL) ) { int len=strlen(txtfile->d_name); //check that the file end with .vtx to avoid accidents and disasters if (strcmp(txtfile->d_name+len-4, ".vtx")==0) { snprintf(fullPath, PATH_MAX, "%s/%s", dir, txtfile->d_name); stat(fullPath, &txtfilestat); filesize=actualFileSize(txtfilestat.st_size); int ret=unlink(fullPath); if (ret==0) bytesDeleted+=filesize; else hadError=ret; } } closedir(d); rmdir(dir); } else { if (!reportedError) { esyslog("OSD-Teletext: Error opening teletext storage subdirectory \"%s\": %s", dir, strerror(errno)); reportedError=true; } } if (hadError && !reportedError) { esyslog("OSD-Teletext: Error removing teletext storage subdirectory \"%s\": %s", dir, strerror(hadError)); reportedError=true; } return bytesDeleted; }
static QIcon readIconFrom(const QByteArray& path, const QByteArray& iconname, int depth = 0) { if (path.isEmpty() || depth > MAX_ICON_RECURSE_DEPTH) return QIcon(); QByteArray fn; static const char* exts[] = { ".xpm", ".png", 0 }; for (int i = 0; ; ++i) { if (!exts[i]) break; fn = path + iconname + exts[i]; if (QFile::exists(QString::fromLocal8Bit(fn.constData(), fn.size()))) { QIcon icn(QString::fromLocal8Bit(fn.constData(), fn.size())); return icn; } } QIcon icn; DIR *dir = opendir(path.constData()); if (!dir) return QIcon(); struct dirent d, *res; while (readdir_r(dir, &d, &res) == 0 && res != 0) { if (d.d_type == DT_DIR) { if (strcmp(d.d_name, ".") && strcmp(d.d_name, "..")) { icn = readIconFrom(path + QByteArray(d.d_name) + '/', iconname, depth + 1); if (!icn.isNull()) { closedir(dir); return icn; } } } } closedir(dir); return QIcon(); }
/** * read the next directory entry in the directory stream * * @param aDir pointer to the directory stream object * @param aEntryName pointer to the constant string object to get the file name * @return result code * * The returned file name is pointer to the internal buffer * of directory stream object. * So, the content of the file name should not be modified. * The file name is always null terminated. * * it returns #ACP_RC_EOF if there is no more file in the directory */ ACP_EXPORT acp_rc_t acpDirRead(acp_dir_t *aDir, acp_char_t **aEntryName) { struct dirent *sEntry = NULL; acp_sint32_t sRet; ACP_RC_SET_OS_ERROR(ACP_RC_SUCCESS); sRet = readdir_r(aDir->mHandle, aDir->mEntry, &sEntry); if (sRet != 0) { #if defined(ALTI_CFG_OS_AIX) if (ACP_RC_GET_OS_ERROR() != ACP_RC_SUCCESS) { return ACP_RC_GET_OS_ERROR(); } else { return ACP_RC_EOF; } #else return sRet; #endif } else { if (sEntry == NULL) { return ACP_RC_EOF; } else { *aEntryName = sEntry->d_name; return ACP_RC_SUCCESS; } } }
void Storage::freeSpace() { //there might be a situation where only the current directory is left and //occupies the whole space. We cannot delete anything. Don't waste time scanning. if (failedFreeSpace) return; //printf("freeSpace()\n"); time_t min=time(0); char minDir[PATH_MAX]; char fullPath[PATH_MAX]; DIR *top=opendir(getRootDir()); if (top) { int haveDir=0; struct dirent *chandir, path; struct stat chandirstat; while ( (!readdir_r(top, &path, &chandir) && chandir != NULL) ) { if (strcmp(chandir->d_name, "..")==0 || strcmp(chandir->d_name, ".")==0) continue; snprintf(fullPath, PATH_MAX, "%s/%s", getRootDir(), chandir->d_name); if (stat(fullPath, &chandirstat)==0) { if (S_ISDIR(chandirstat.st_mode)) { if (chandirstat.st_ctime < min && strcmp(fullPath, currentDir)) { min=chandirstat.st_ctime; strcpy(minDir, fullPath); haveDir++; } } } } closedir(top); //if haveDir, only current directory present, which must not be deleted if (haveDir>=2) byteCount-=cleanSubDir(minDir); else failedFreeSpace=true; } }
/** * process a directory for plugins * * @returns TRUE if at least one plugin loaded successfully */ int load_plugin_dir(char *plugindir) { DIR *d_plugin; char de[sizeof(struct dirent) + MAXNAMLEN + 1]; /* ?? solaris */ struct dirent *pde; char *pext; char *perr=NULL; int loaded=FALSE; char plugin[PATH_MAX]; if((d_plugin=opendir(plugindir)) == NULL) { DPRINTF(E_LOG,L_MAIN,"Error opening plugin dir %s. Ignoring\n", plugindir); return FALSE; } else { while((readdir_r(d_plugin,(struct dirent *)de,&pde) != 1) && pde) { pext = strrchr(pde->d_name,'.'); if((pext) && ((strcasecmp(pext,".so") == 0) || (strcasecmp(pext,".dylib") == 0) || (strcasecmp(pext,".dll") == 0))) { /* must be a plugin */ snprintf(plugin,PATH_MAX,"%s%c%s",plugindir, PATHSEP,pde->d_name); if(plugin_load(&perr,plugin) != PLUGIN_E_SUCCESS) { DPRINTF(E_LOG,L_MAIN,"Error loading plugin %s: %s\n", plugin,perr); free(perr); perr = NULL; } else { loaded = TRUE; } } } closedir(d_plugin); } return loaded; }
std::string findInDir(std::string parent, std::list<std::string> remainingPath, const char DIR_SEP) { Directory d(parent); std::string name = remainingPath.front(); remainingPath.pop_front(); //Strip out any excess blank entries (otherwise paths like "./directory//file" would break) while (name == "") { if (remainingPath.empty()) return parent; name = remainingPath.front(); remainingPath.pop_front(); } struct dirent entry , *result = NULL; while (true) { int err = readdir_r(d.d, &entry, &result); if (err) { std::cerr << "Readdir() failed with \"" << err << "\"\n"; return ""; } if (!result) { break; } std::string entName(entry.d_name); if (Strings::CompareCaseInsensitive(name, entName) == 0) { std::string entPath = parent + DIR_SEP + entName; if (remainingPath.empty()) return entPath; else return findInDir(entPath, remainingPath, DIR_SEP); } } return ""; }
static void removeUidProcessGroups(const char *uid_path) { std::unique_ptr<DIR, decltype(&closedir)> uid(opendir(uid_path), closedir); if (uid != NULL) { struct dirent cur; struct dirent *dir; while ((readdir_r(uid.get(), &cur, &dir) == 0) && dir) { char path[PROCESSGROUP_MAX_PATH_LEN]; if (dir->d_type != DT_DIR) { continue; } if (strncmp(dir->d_name, PROCESSGROUP_PID_PREFIX, strlen(PROCESSGROUP_PID_PREFIX))) { continue; } snprintf(path, sizeof(path), "%s/%s", uid_path, dir->d_name); SLOGV("removing %s\n", path); rmdir(path); } } }
int Storage::doCleanUp() { DIR *top=opendir(root); int pagesDeleted=0; if (top) { struct dirent *chandir, path; struct stat chandirstat; char fullPath[PATH_MAX]; while ( (!readdir_r(top, &path, &chandir) && chandir != NULL) ) { if (strcmp(chandir->d_name, "..")==0 || strcmp(chandir->d_name, ".")==0) continue; snprintf(fullPath, PATH_MAX, "%s/%s", root, chandir->d_name); if (stat(fullPath, &chandirstat)==0) { if (S_ISDIR(chandirstat.st_mode)) { pagesDeleted+=cleanSubDir(fullPath); } } } closedir(top); } else { esyslog("OSD-Teletext: Error opening teletext storage directory \"%s\": %s", root, strerror(errno)); } return pagesDeleted; }
int ioctx_readdir_r(IOCtx ioctx, struct diod_dirent *entry, struct diod_dirent **result) { int r; struct dirent* rd_result; if (!ioctx->dir) return EINVAL; r = readdir_r (ioctx->dir, &entry->dir_entry, &rd_result); if (r==0) { /* success */ /* Does the same to diod_dirent as readdir_r() does to dirent */ if (rd_result == NULL) *result = NULL; else *result = entry; #ifdef _DIRENT_HAVE_D_OFF entry->d_off = entry->dir_entry.d_off; #else entry->d_off = telldir (ioctx->dir); #endif } return r; }
static bool find(String8& result, const String8& pattern, const char* const search, bool exact) { if (exact) { String8 absolutePath; absolutePath.appendFormat("%s/%s.so", search, pattern.string()); if (!access(absolutePath.string(), R_OK)) { result = absolutePath; return true; } return false; } DIR* d = opendir(search); if (d != NULL) { struct dirent cur; struct dirent* e; while (readdir_r(d, &cur, &e) == 0 && e) { if (e->d_type == DT_DIR) { continue; } if (!strcmp(e->d_name, "libGLES_android.so")) { // always skip the software renderer continue; } if (strstr(e->d_name, pattern.string()) == e->d_name) { if (!strcmp(e->d_name + strlen(e->d_name) - 3, ".so")) { result.clear(); result.appendFormat("%s/%s", search, e->d_name); closedir(d); return true; } } } closedir(d); } return false; }
void CommandListener::AsecCmd::listAsecsInDirectory(SocketClient *cli, const char *directory) { DIR *d = opendir(directory); if (!d) { cli->sendMsg(ResponseCode::OperationFailed, "Failed to open asec dir", true); return; } size_t dirent_len = offsetof(struct dirent, d_name) + fpathconf(dirfd(d), _PC_NAME_MAX) + 1; struct dirent *dent = (struct dirent *) malloc(dirent_len); if (dent == NULL) { cli->sendMsg(ResponseCode::OperationFailed, "Failed to allocate memory", true); return; } struct dirent *result; while (!readdir_r(d, dent, &result) && result != NULL) { if (dent->d_name[0] == '.') continue; if (dent->d_type != DT_REG) continue; size_t name_len = strlen(dent->d_name); if (name_len > 5 && name_len < 260 && !strcmp(&dent->d_name[name_len - 5], ".asec")) { char id[255]; memset(id, 0, sizeof(id)); strlcpy(id, dent->d_name, name_len - 4); cli->sendMsg(ResponseCode::AsecListResult, id, false); } } closedir(d); free(dent); }
int scandir(const char *path, struct dirent ***dlist, int (*filter)(struct dirent *d), int (*cmp)(const void *, const void *)) { int ret = 0; DIR *dir = NULL; struct dirent *ent = NULL; struct dirent *res = NULL; int nentries = 0; struct dirent **dentries = NULL; if(!path || !dlist || !cmp) return -1; dir = opendir(path); if(!dir) return -1; ent = malloc(sizeof(*ent)); assert(ent != NULL); while( !(ret = readdir_r(dir, ent, &res)) ) { if(!res) break; if(!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) continue; if(!filter || filter(ent) == 1) { dentries = realloc(dentries, sizeof(*dentries) * (nentries + 1)); assert(dentries != NULL); dentries[nentries] = malloc(sizeof(*ent)); assert(dentries[nentries] != NULL); memcpy(dentries[nentries++], ent, sizeof(*ent)); } } if(ret) return -1; if(!nentries) return 0; *dlist = dentries; qsort(dentries, nentries, sizeof(*dentries), cmp); return nentries; }
bool Filesystem::deleteDirectory(std::string path) { DIR *dir; struct dirent *ent = NULL; struct dirent *entryp = NULL; if ((dir = opendir(path.c_str())) == NULL) { printf("Cannot open dir %s\n",path.c_str()); return false; } int name_max = pathconf(path.c_str(), _PC_NAME_MAX); if (name_max == -1) /* Limit not defined, or error */ name_max = 255; /* Take a guess */ int len = offsetof(struct dirent, d_name) + name_max + 1; entryp = (struct dirent*)malloc(len); while (readdir_r(dir,entryp,&ent) == 0 && ent != NULL) { std::string entry( ent->d_name ); if(entry == "." || entry == "..") continue; struct stat st; stat(std::string(path+"/"+ent->d_name).c_str(),&st); if(st.st_mode & S_IFDIR) { deleteDirectory(std::string(path+"/"+ent->d_name)); } else { remove(std::string(path+"/"+ent->d_name).c_str()); } } free(entryp); closedir(dir); rmdir(path.c_str()); return true; }
static int pkcs8_dir_list(void *_handle, dnssec_list_t **list_ptr) { if (!_handle || !list_ptr) { return DNSSEC_EINVAL; } pkcs8_dir_handle_t *handle = _handle; _cleanup_closedir_ DIR *dir = opendir(handle->dir_name); if (!dir) { return DNSSEC_NOT_FOUND; } dnssec_list_t *list = dnssec_list_new(); if (!list) { return DNSSEC_ENOMEM; } int error; struct dirent entry, *result; while (error = readdir_r(dir, &entry, &result), error == 0 && result) { char *keyid = filename_to_keyid(entry.d_name); if (keyid) { dnssec_list_append(list, keyid); } } if (error != 0) { dnssec_list_free_full(list, NULL, NULL); return dnssec_errno_to_error(error); } *list_ptr = list; return DNSSEC_EOK; }