Created
January 11, 2019 20:53
-
-
Save andyrudoff/239652ee42109d0af994127f689840ba to your computer and use it in GitHub Desktop.
trivial example showing how to use opendir+openat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* opendir_and_openat.c -- trivial example showing how to use opendir+openat | |
* | |
* usage: a.out path-to-directory | |
*/ | |
#include <stdio.h> | |
#include <dirent.h> | |
#include <err.h> | |
#include <fcntl.h> | |
#include <sys/stat.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 2) { | |
fprintf(stderr, "usage: %s dirname\n", argv[0]); | |
exit(1); | |
} | |
int dfd = open(argv[1], O_RDONLY); | |
if (dfd < 0) | |
err(1, argv[1]); | |
DIR *dirp = fdopendir(dfd); | |
if (dirp == NULL) | |
err(1, "opendir: %s", argv[1]); | |
struct dirent *dp; | |
while ((dp = readdir(dirp)) != NULL) { | |
if ((strcmp(dp->d_name, ".") == 0) || | |
(strcmp(dp->d_name, "..") == 0)) | |
continue; | |
struct stat stbuf; | |
int fd = openat(dfd, dp->d_name, O_RDONLY); | |
if (fd < 0 || fstat(fd, &stbuf) < 0) { | |
warn("skipping %s/%s", argv[1], dp->d_name); | |
continue; | |
} | |
if (!S_ISREG(stbuf.st_mode)) { | |
warnx("%s: not a regular file", dp->d_name); | |
continue; | |
} | |
printf("processing file \"%s\"\n", dp->d_name); | |
close(fd); | |
} | |
closedir(dirp); | |
printf("done.\n"); | |
exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment