Created
October 30, 2011 01:21
-
-
Save malloc47/1325334 to your computer and use it in GitHub Desktop.
listing files with posix C calls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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