~ubuntu-branches/ubuntu/vivid/cctools/vivid

« back to all changes in this revision

Viewing changes to dttools/src/sort_dir.c

  • Committer: Bazaar Package Importer
  • Author(s): Michael Hanke
  • Date: 2011-05-07 09:05:00 UTC
  • Revision ID: james.westby@ubuntu.com-20110507090500-lqpmdtwndor6e7os
Tags: upstream-3.3.2
ImportĀ upstreamĀ versionĀ 3.3.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
Copyright (C) 2003-2004 Douglas Thain and the University of Wisconsin
 
3
Copyright (C) 2005- The University of Notre Dame
 
4
This software is distributed under the GNU General Public License.
 
5
See the file COPYING for details.
 
6
*/
 
7
 
 
8
#include "sort_dir.h"
 
9
 
 
10
#include <dirent.h>
 
11
#include <string.h>
 
12
#include <stdlib.h>
 
13
#include <dirent.h>
 
14
 
 
15
int sort_dir( const char *dirname, char ***list, int (*sort) ( const char *a, const char *b ) )
 
16
{
 
17
        DIR *dir=0;
 
18
        struct dirent *d;
 
19
        int size=10;
 
20
        int used=0;
 
21
        char *s;
 
22
 
 
23
        *list = malloc(size*sizeof(char*));
 
24
        if(!*list) goto failure;
 
25
 
 
26
        dir = opendir(dirname);
 
27
        if(!dir) goto failure;
 
28
 
 
29
        while( (d = readdir(dir)) ) {
 
30
                if(used>=size) {
 
31
                        size *=2;
 
32
                        *list = realloc(*list,sizeof(char*)*size);
 
33
                        if(!*list) goto failure;
 
34
                }
 
35
 
 
36
                s = strdup(d->d_name);
 
37
                if(!s) goto failure;
 
38
 
 
39
                (*list)[used++] = s;
 
40
        }
 
41
 
 
42
        if(sort) {
 
43
                qsort( *list, used, sizeof(char*), (void*) sort );
 
44
        }
 
45
 
 
46
        closedir(dir);
 
47
        (*list)[used] = 0;
 
48
        return 1;
 
49
 
 
50
        failure:
 
51
        if(*list) {
 
52
                (*list)[used] = 0;
 
53
                sort_dir_free(*list);
 
54
                *list = 0;
 
55
        } 
 
56
        if(dir) closedir(dir);
 
57
        return 0;
 
58
}
 
59
 
 
60
void sort_dir_free( char **list )
 
61
{
 
62
        int i;
 
63
        if(list) {
 
64
                for(i=0;list[i];i++) {
 
65
                        if(list[i]) free(list[i]);
 
66
                }
 
67
                free(list);
 
68
        }
 
69
}
 
70