Skip to content

Instantly share code, notes, and snippets.

@moreati
Created September 14, 2022 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moreati/291d17593c837e83950bde8a4f8daa03 to your computer and use it in GitHub Desktop.
Save moreati/291d17593c837e83950bde8a4f8daa03 to your computer and use it in GitHub Desktop.
Example calling scandirat() in glibc
#define _DEFAULT_SOURCE
#define _GNU_SOURCE
#include <dirent.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* Compile with
gcc -Wall -Wextra -O2 scandirat.c -o scandirat
*/
int main(void)
{
struct dirent **namelist;
int dirfd, count;
dirfd = open("/", O_CLOEXEC|O_DIRECTORY|O_RDONLY);
if (dirfd < 0) {
err(EXIT_FAILURE, NULL);
}
count = scandirat(dirfd, ".", &namelist, NULL, alphasort);
if (count < 0) {
perror("scandirat");
err(EXIT_FAILURE, NULL);
}
for (int i=0; i<count; i++) {
printf("%s\n", namelist[i]->d_name);
free(namelist[i]);
}
free(namelist);
close(dirfd);
exit(EXIT_SUCCESS);
}
@moreati
Copy link
Author

moreati commented Sep 14, 2022

alex@bertha:~$ gcc -Wall -Wextra -O2 scandirat.c -o scandirat
alex@bertha:~$ ./scandirat 
.
..
bin
boot
cdrom
dev
...
tmp
usr
var
vmlinuz
vmlinuz.old

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment