tags:

views:

88

answers:

4

Hi, I got a list of files and folders using dirent & stat in C, but they are not in the order I want. I want it will list the directories first then files. Ex:

.
..
[dir1]
[dir2]
[file1]
[file2]

Is there a way to do this with dirent? Or I dont want to manually order the output list. Thanks.

A: 

Make two passes through the dir, first showing only dirs, and in the second showing only files. I'd only do this if you just wants dirs-then-files; if you have some detailed sorting criteria, I'd store the entries in an array and sort it w/ a custom ordering function.

wrang-wrang
A: 

You will need to read them and sort yourself. Or use a different library function which does it for you.

Roger Pate
+2  A: 

You will have to sort them if you use opendir/readdir, but you can use scandir(3) (assuming you're on a *nix system) if you want to get all the directory entries sorted.

Gonzalo
A: 

You can maintain two data structure, one for dir and one for file. Once you start reading directory with dirent, insert into respective structure runtime.

Merge both list in the end with directories and files respectively. This method will finish in one pass O(N) and merge will take just one instruction which is O(1).

Jack