Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "flist.h"
- int main() {
- FList *f;
- f = init_file_list("/");
- get_file_list(f);
- print_file_list(f);
- printf("file count: %li", f->count);
- free_file_list(f);
- return 0;
- }
- FList *init_file_list(const char *path){
- FList *f = (FList*)malloc(sizeof(FList));
- f->count = 0;
- f->path = (char*)malloc(sizeof(char)*(strlen(path)+1));
- strcpy(f->path,path);
- return f;
- }
- void get_file_list(FList *f){
- size_t index = 0;
- recurse_dir(f->path, &(f->files), &(f->count));
- f->files = (char**)malloc(f->count*sizeof(char*));
- recurse_dir(f->path, &(f->files), &index);
- }
- void print_file_list(FList *f){
- size_t i;
- for (i = 0; i < f->count; i++) {
- printf("%s\n", f->files[i]);
- }
- }
- void free_file_list(FList *f){
- size_t i;
- for (i = 0; i < f->count; i++) {
- free((void*)(f->files)[i]);
- }
- free((void*)f->files);
- free((void*)f);
- }
- void recurse_dir(char *path, char ***files, size_t *index){
- char *newpath;
- struct dirent *ent;
- DIR *dir = opendir(path);
- if (dir == NULL) {
- perror("erro ao abrir diretorio");
- return;
- }
- while ((ent = readdir(dir)) != NULL){
- if (ent->d_type == DT_DIR && strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0 && (ent->d_name[0] != '.')) {
- build_path(&(newpath), path, ent->d_name);
- recurse_dir(newpath, files, index);
- free((void *)newpath);
- }
- else if (ent->d_type == DT_REG && ent->d_name[0] != '.') {
- if(*files != NULL){
- build_path(&(newpath), path, ent->d_name);
- *((*files) + *index) = newpath;
- }
- (*index)++;
- }
- }
- closedir(dir);
- }
- void build_path(char **fullpath, const char *path, const char *filename){
- *fullpath = malloc(strlen(path) + strlen(filename) + 2);
- if(*fullpath == NULL){
- perror("erro ao alocar memoria para os enderecos de arquivo");
- exit(1);
- }
- strcpy(*fullpath, path);
- strcat(*fullpath, "/");
- strcat(*fullpath, filename);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement