Skip to content

Commit

Permalink
add a file demo
Browse files Browse the repository at this point in the history
  • Loading branch information
eyelash committed Sep 18, 2024
1 parent ec60c06 commit e00e38b
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
3 changes: 3 additions & 0 deletions demos/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ target_link_libraries(draw gral)
add_executable(events events.c)
target_link_libraries(events gral)

add_executable(file file.c)
target_link_libraries(file gral)

add_executable(file_dialogs file_dialogs.c)
target_link_libraries(file_dialogs gral)

Expand Down
102 changes: 102 additions & 0 deletions demos/file.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#include <gral.h>
#include <stdio.h>
#include <string.h>

static void command_cat(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
struct gral_file *file = gral_file_open_read(argv[2]);
if (!file) {
printf("invalid file\n");
return;
}
size_t size = gral_file_get_size(file);
void *data = gral_file_map(file, size);
gral_file_close(file);
gral_file_write(gral_file_get_standard_output(), data, size);
gral_file_unmap(data, size);
}

static void ls_callback(char const *name, void *user_data) {
printf("%s\n", name);
}

static void command_ls(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
gral_directory_iterate(argv[2], &ls_callback, 0);
}

static void command_mkdir(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
gral_directory_create(argv[2]);
}

static void command_rm(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
gral_file_remove(argv[2]);
}

static void command_rmdir(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
gral_directory_remove(argv[2]);
}

static void command_stat(int argc, char **argv) {
if (argc < 3) {
printf("missing argument\n");
return;
}
int file_type = gral_file_get_type(argv[2]);
if (file_type == GRAL_FILE_TYPE_REGULAR) {
printf("regular\n");
}
else if (file_type == GRAL_FILE_TYPE_DIRECTORY) {
printf("directory\n");
}
else if (file_type == GRAL_FILE_TYPE_INVALID) {
printf("invalid\n");
}
}

int main(int argc, char **argv) {
if (argc < 2) {
printf("missing command\n");
return 0;
}
if (strcmp(argv[1], "cat") == 0) {
command_cat(argc, argv);
}
else if (strcmp(argv[1], "ls") == 0) {
command_ls(argc, argv);
}
else if (strcmp(argv[1], "mkdir") == 0) {
command_mkdir(argc, argv);
}
else if (strcmp(argv[1], "rm") == 0) {
command_rm(argc, argv);
}
else if (strcmp(argv[1], "rmdir") == 0) {
command_rmdir(argc, argv);
}
else if (strcmp(argv[1], "stat") == 0) {
command_stat(argc, argv);
}
else {
printf("invalid command\n");
}
return 0;
}

0 comments on commit e00e38b

Please sign in to comment.