From 29db1ce52445a809ae9e4f7db2a19ccfa9904e31 Mon Sep 17 00:00:00 2001 From: Soispha Date: Mon, 21 Aug 2023 01:24:12 +0200 Subject: Feat(c): Init --- c/src/main.c | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 c/src/main.c (limited to 'c/src') diff --git a/c/src/main.c b/c/src/main.c new file mode 100644 index 0000000..1b9afcd --- /dev/null +++ b/c/src/main.c @@ -0,0 +1,88 @@ +#include +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include "rename.h" + +bool file_exists(const char *filename) { return (access(filename, F_OK) == 0); } + +char *update_file_name(char *old_file_name, FILE *newin) { + fprintf(newin, "%s", old_file_name); + + char *new_file_name = readline("New name: "); + + return new_file_name; +} + +bool ask_for_confirmation(char *prompt) { + bool return_value = false; + char *confirmation = readline(prompt); + + if (strcmp(confirmation, "y") == 0) + return_value = true; + + free(confirmation); + return return_value; +} + +int main() { + const char *newin_name = tempnam(NULL, NULL); + FILE *newin = fopen(newin_name, "w"); + if (!newin) + perror("Failed to create tempfile"); + FILE *_ = freopen(newin_name, "r", stdin); + + char *old_file_name = getenv("f"); + old_file_name = basename(old_file_name); + char *new_file_name = (char *)NULL; + char *current_file_name = (char *)malloc(sizeof(char) * 255); + const char *original_file_name = getenv("f"); + + int done = false; + + while (!done) { + if (old_file_name) { + new_file_name = update_file_name(old_file_name, newin); + old_file_name = (char *)NULL; + } else { + new_file_name = update_file_name(current_file_name, newin); + } + if (file_exists(new_file_name)) { + char *prompt = malloc(sizeof(char) * (255 + 43)); + snprintf(prompt, 43 + 255, + "Name (`%s`) already exists, overwrite [y|N]: ", new_file_name); + if (ask_for_confirmation(prompt)) + done = true; + free(prompt); + } else if (new_file_name[0] == '\0') { + /* new_file_name is emtpy */ + if (ask_for_confirmation("Name is empty, accept nevertheless [y|N]: ")) + done = true; + } else { + done = true; + } + if (!done) { + strcpy(current_file_name, new_file_name); + free(new_file_name); + new_file_name = (char *)NULL; + } + } + + // rename old file with new name + if (rename(original_file_name, new_file_name) == 0) { + printf("File renamed successfully.\n"); + } else { + perror("Unable to rename files. Please check files exist and you have " + "permissions to modify files"); + } + free(new_file_name); +} -- cgit 1.4.1