I'm trying to perform DFS on a folder that can contain sub folders. The goal is to locate all .txt
files from a directory. I need to find the .txt
files in the order that DFS finds them and preserve the order of files in a folder.
Currently my code for scanning a directory uses the scandir()
function:
int n = scandir(path, &namelist, NULL, alphasort);
This sorts the files in a folder in alphabetical order, which isn't exactly what I want.
Edit: I've tried using opendir() and readdir() but this is accessing files in a seemingly random order.
According to versionsort man page
int versionsort(const void *a, const void *b);
can be passed as a callback to scandir()
and is declared in dirent.h
.
From the same page linked above:
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
scandir()
,alphasort()
: _BSD_SOURCE || _SVID_SOURCE
versionsort()
: _GNU_SOURCE.
These macros need to be defined before dirent.h
inclusion in order to enable the specific feature.
From the same page linked above:
Versions
versionsort()
was added to glibc in version 2.1.
Please refer to this question to learn how to check your glibc version.