scandir()

Scan a directory

Synopsis:

#include <sys/types.h>
#include <sys/dir.h>

int scandir( char * dirname, 
             struct direct * (* namelist[]),
             int (*select)(struct dirent *),
             int (*compar)(const void *,const void *) );

Since:

BlackBerry 10.0.0

Arguments:

dirname
The name of the directory that you want to scan.
namelist
A pointer to a location where scandir() can store a pointer to the array of directory entries (of type struct direct *) that it builds.
select
A pointer to a user-supplied subroutine that scandir() calls to select which entries to included in the array. The select routine is passed a pointer to a directory entry (a struct dirent ) and should return a nonzero value if the directory entry is to be included in the array.

If select is NULL, all the directory entries are included.

compar
A pointer to a user-supplied subroutine that's passed to qsort() to sort the completed array. If this pointer is NULL, the array isn't sorted.

You can use alphasort() as the compar parameter to sort the array alphabetically.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

This function is in libc.a, but not in libc.so (in order to save space).

Description:

The scandir() function reads the directory dirname and builds an array of pointers to directory entries, using malloc() to allocate the space. The scandir() function returns the number of entries in the array, and stores a pointer to the array in the location referenced by namelist.

Don't confuse the direct and dirent structures:

  • The entries in the array are pointers to direct structures.
  • The argument to the select function is a pointer to a dirent structure.
  • The arguments to the compar() function are used as pointers to direct structures.

The struct direct is defined as:

struct direct {
    unsigned long d_fileno;
    unsigned short d_reclen;
    unsigned short d_namlen;
    char d_name[1];
};

You can deallocate the memory allocated for the array by calling free(). Free each pointer in the array, and then free the array itself.

Returns:

The number of entries in the array, or -1 if the directory can't be opened for reading, or malloc() can't allocate enough memory to hold all the data structures.

Classification:

Legacy Unix

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler Yes
Thread Yes

Last modified: 2014-06-24



Got questions about leaving a comment? Get answers from our Disqus FAQ.

comments powered by Disqus