aboutsummaryrefslogtreecommitdiff
path: root/file.c
diff options
context:
space:
mode:
Diffstat (limited to 'file.c')
-rw-r--r--file.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/file.c b/file.c
new file mode 100644
index 0000000..eebc49d
--- /dev/null
+++ b/file.c
@@ -0,0 +1,67 @@
+#include "file.h"
+#include <dirent.h>
+#include <libgen.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+
+char *get_filename_ext(char *file_name)
+{
+ char *dot = strrchr(file_name, '.');
+ if (!dot || dot == file_name)
+ return "";
+ return dot + 1;
+}
+
+int image_filter(const struct dirent *dir)
+{
+ char *ext = get_filename_ext(strdup(dir->d_name));
+ if (dir->d_type == DT_REG && (!strcmp(ext, "png") || !strcmp(ext, "jpg"))) {
+ return 1;
+ }
+ return 0;
+}
+
+int scan(const char *file_name)
+{
+ struct dirent **name_list;
+ char *dir_name = dirname(strdup(file_name));
+ size_t dir_name_len = strlen(dir_name);
+ file_list_count = scandir(dir_name, &name_list, image_filter, alphasort);
+ if (file_list_count < 0) {
+ return -1;
+ }
+
+ file_list = malloc(file_list_count * sizeof(char *));
+ char *file_basename = basename(strdup(file_name));
+ int i = 0;
+ while (i < file_list_count) {
+ if (!strcmp(file_basename, name_list[i]->d_name))
+ curr_file_index = i;
+ file_list[i] = malloc(
+ (strlen(name_list[i]->d_name) + dir_name_len + 2) * sizeof(char *));
+ sprintf(file_list[i], "%s/%s", dir_name, name_list[i]->d_name);
+ free(name_list[i]);
+ i++;
+ }
+ free(name_list);
+
+ return 0;
+}
+
+char *get_next_file()
+{
+ if (curr_file_index >= file_list_count - 1) {
+ return NULL;
+ }
+ return file_list[++curr_file_index];
+}
+
+char *get_prev_file()
+{
+ if (curr_file_index <= 0) {
+ return NULL;
+ }
+ return file_list[--curr_file_index];
+}