HTMLify
search.c
Views: 8 | Author: abh
#include <dirent.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include "search.h"
SearchResult search(const char *string, const char *search_dir, void (*callback)(int, int, int, char*)) {
char **results = NULL;
DIR *d;
struct dirent *entry;
char **dir_queue = NULL;
char *sdir, *current_dir;
int queueleft, files_checked=0, dirs_checked=0, files_matched=0;
dir_queue = realloc(dir_queue, sizeof(char*));
dir_queue[0] = malloc(strlen(search_dir)+1);
strcpy(dir_queue[0], search_dir);
queueleft = 1;
while (queueleft) {
sdir = dir_queue[0];
d = opendir(sdir);
current_dir = malloc(strlen(sdir)+1);
strcpy(current_dir, sdir);
while (d != NULL && (entry = readdir(d)) != NULL) {
if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
char *ndir = malloc(strlen(sdir) + strlen(entry->d_name) + 2);
if (sdir[strlen(sdir)-1] == '/') {
sprintf(ndir, "%s%s", sdir, entry->d_name);
} else {
sprintf(ndir, "%s/%s", sdir, entry->d_name);
}
dir_queue = realloc(dir_queue, (sizeof(char*)*(queueleft+1)));
dir_queue[queueleft] = malloc(strlen(ndir)+1);
strcpy(dir_queue[queueleft], ndir);
queueleft++;
free(ndir);
} else {
if (strstr(entry->d_name, string)) {
results = realloc(results, sizeof(char*)*(files_matched+1));
results[files_matched] = strdup(entry->d_name);
files_matched++;
}
files_checked++;
}
}
closedir(d);
if (callback != NULL)
callback(files_checked, dirs_checked, files_matched, current_dir);
free(current_dir);
dirs_checked++;
for (int i=0; i<queueleft-1; i++)
dir_queue[i] = dir_queue[i+1];
queueleft--;
dir_queue = realloc(dir_queue, sizeof(char*)*queueleft);
}
SearchResult search_result = { results, files_matched };
return search_result;
}