Skip to content

Instantly share code, notes, and snippets.

@malloc47 malloc47/ls_d.cpp
Created Oct 30, 2011

Embed
What would you like to do?
listing files with posix C calls
// Lists directories in the given path
list_t ls_d(string path) {
list_t output;
DIR* dirp = opendir(path.c_str());
struct dirent *file;
if(dirp==NULL)
return list_t();
while ((file = readdir(dirp)) != NULL) {
string name(file->d_name);
if(!name.compare(".") || !name.compare("..")) continue;
struct stat st;
if(stat((path+"/"+name).c_str(),&st)) continue;
if(S_ISDIR(st.st_mode)) {
output.push_back(string(file->d_name)+"/");
}
}
closedir(dirp);
if(path.compare("/"))
output.push_back("../");
output.push_back("./");
return output;
}
// Lists files in the given path
// list_t is a typedef for: vector<string>
// You will likely need these includes, among others
#include <vector>
#include <string>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
list_t ls_f(string path) {
list_t output;
DIR* dirp = opendir(path.c_str());
struct dirent *file;
if(dirp==NULL)
return list_t();
while ((file = readdir(dirp)) != NULL) {
string name(file->d_name);
struct stat st;
if(stat((path+"/"+name).c_str(),&st)) continue;
if(S_ISREG(st.st_mode)) {
if(filters.empty())
output.push_back(string(file->d_name));
else
FOR_l(i,filters)
if(string(file->d_name).find(filters[i]) !=string::npos) {
output.push_back(string(file->d_name));
break;
}
}
}
closedir(dirp);
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.