Originally Posted by
Salem
Start with the basics first, like
- read the entries in the current directory
- determine whether they're files or directories
- make the function recursive on the directory entries
- add the storage using malloc
BTW, there's a FAQ entry to do just that.
I've managed to do what you mentioned in your previous post but now there is a problem where I'll get a segmentation fault error. I'm sure it has to do with the [code]mem_alloc()[\code] method. Can anybody point out the problem because I don't see it.
Code:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
DIR* str;
struct dirent **dir_entries;
off_t total_size;
int str_size = 0;
int str_memalloc = 0;
int dir_size = 0;
int dir_memalloc = 0;
void collect_entries();
void mem_alloc();
void print_entries();
void print_entries() {
for(int i = 0; i < dir_size; i++) {
printf("%s\n",dir_entries[i] -> d_name);
}
}
void collect_entries(const char* p_name) {
DIR* temp_dir = opendir(p_name);
struct dirent* temp_ent;
struct stat temp_buf;
while(1) {
if( (temp_ent = readdir(temp_dir)) == NULL) {
return;
}
stat(temp_ent -> d_name, &temp_buf);
if( strcmp(temp_ent -> d_name, "..") == 0
|| strcmp(temp_ent -> d_name, ".") == 0) {
continue;
}
else if(S_ISDIR(temp_buf.st_mode) != 0) {
mem_alloc(temp_ent);
char path[256];
strcpy(path, temp_ent -> d_name);
printf("%s\n", path);
collect_entries(path);
}
else {
printf("%s\n",temp_ent->d_name);
mem_alloc(temp_ent);
}
}
closedir(str);
}
void mem_alloc(struct dirent* temp_ent) {
if(dir_size == dir_memalloc) {
if(dir_memalloc == 0) {
dir_memalloc = 3;
}
else
dir_memalloc += 8;
void** temp = realloc(dir_entries, dir_memalloc *
sizeof(struct dirent*));
if(!temp) {
perror("Memory allocation failed errno: ");
}
dir_entries = (struct dirent**) temp;
}
dir_entries[dir_size++] = temp_ent;
}
int main() {
collect_entries(".");
print_entries();
return 0;
}