#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); }