Saturday, December 19, 2009

reading a directory



Read a Directory

This code reads a directory passed as a string and returns a pointer to a special struct called Directory.

Snippet



  1. /*

  2. * dirlist.c


  3. *

  4.  * mani

  5. */

  6.  

  7. #include <dirent.h>

  8. #include <stdio.h>

  9. #include <string.h>


  10. #include <stdlib.h>

  11. #include "dirlist.h"

  12.  

  13. Directory* readDirectory(char* dirname)

  14. {

  15.         Directory* d = (Directory*) malloc(sizeof(Directory) );


  16.         d->files = (char**) malloc(0);

  17.         d->len = 0;


  18.         d->files[d->len] = 0;

  19.         DIR *dir;


  20.         struct dirent *de;

  21.         dir = opendir(dirname);

  22.         if (dir == NULL)


  23.         {

  24.                 printf("Could not open directry \"%s\"\n", dirname);


  25.                 exit (1);

  26.         }


  27.        

  28.         while ( (de = readdir(dir) ) != NULL )


  29.         {

  30.                 /*

  31.                 * We need to resize the char** in the Directory struct


  32.                 * and then allocate enough space in the char* for the file name

  33.                 * I use sprintf instead of strcpy, or strncpy for no real reason


  34.                 */

  35.                 d->files = (char**) realloc(d->files, sizeof(char*) * ++(d->len) );


  36.                 d->files[d->len - 1] = (char*) malloc (sizeof(char) * (strlen(de->d_name) + 1) );


  37.                 sprintf(d->files[d->len - 1], "%s", de->d_name);


  38.         }

  39.         closedir(dir);

  40.         return d;


  41. }

  42.  

  43.  








No comments:

Post a Comment