Skip to content

Instantly share code, notes, and snippets.

@voldyman
Created February 3, 2019 16:37
Show Gist options
  • Save voldyman/3e662487d30b3945c26333d7b89015c3 to your computer and use it in GitHub Desktop.
Save voldyman/3e662487d30b3945c26333d7b89015c3 to your computer and use it in GitHub Desktop.
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
static
bool startswith(const char* str, const char* prefix) {
if ((str == NULL) || (prefix == NULL)) {
return false;
}
size_t str_len = strlen(str);
size_t prefix_len = strlen(prefix);
if (prefix_len > str_len) {
return false;
}
return strncmp(prefix, str, prefix_len) == 0;
}
typedef void(*DirVisitor)(void* ctx, const struct dirent*);
static
bool listdir(const char* dirname, DirVisitor visitor, void* ctx) {
DIR* dir = opendir(dirname);
if (dir == NULL) {
fprintf(stderr, "Couldn't open directory '%s': %s\n", dirname, strerror(errno));
return false;
}
struct dirent* dp;
while ((dp = readdir(dir)) != NULL) {
if (!startswith(dp->d_name, "."))
visitor(ctx, dp);
}
closedir(dir);
return true;
}
void dir_printer(void* ctx, const struct dirent* dp) {
const char* parent_dir = (const char*) ctx;
fprintf(stdout, "%s/%s\n", parent_dir, dp->d_name);
}
char* dir_path(const char* dir) {
const size_t maxlen = 4096;
char* result;
if ((result = realpath(dir, NULL)) == NULL) {
fprintf(stderr, "Couldn't get path for dir '%s': %s\n", dir, strerror(errno));
return NULL;
}
return result;
}
int main(int argc, char* argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <dirname>\n", argv[0]);
return EXIT_FAILURE;
}
char* path = dir_path(argv[1]);
int result = EXIT_SUCCESS;
do {
if (!listdir(path, dir_printer, (void*)path)) {
fprintf(stderr, "Failed\n");
result = EXIT_FAILURE;
break;
}
} while(false);
free(path);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment