Read a Directory
This code reads a directory passed as a string and returns a pointer to a special struct called Directory.
This code reads a directory passed as a string and returns a pointer to a special struct called Directory.
Snippet
- /*
- * dirlist.c
- *
- * mani
- */
- #include <dirent.h>
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include "dirlist.h"
- Directory* readDirectory(char* dirname)
- {
- Directory* d = (Directory*) malloc(sizeof(Directory) );
- d->files = (char**) malloc(0);
- d->len = 0;
- d->files[d->len] = 0;
- DIR *dir;
- struct dirent *de;
- dir = opendir(dirname);
- if (dir == NULL)
- {
- exit (1);
- }
- while ( (de = readdir(dir) ) != NULL )
- {
- /*
- * We need to resize the char** in the Directory struct
- * and then allocate enough space in the char* for the file name
- * I use sprintf instead of strcpy, or strncpy for no real reason
- */
- d->files = (char**) realloc(d->files, sizeof(char*) * ++(d->len) );
- d->files[d->len - 1] = (char*) malloc (sizeof(char) * (strlen(de->d_name) + 1) );
- sprintf(d->files[d->len - 1], "%s", de->d_name);
- }
- closedir(dir);
- return d;
- }
No comments:
Post a Comment