├── .github ├── FUNDING.yml └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── CNAME ├── LICENSE ├── README.md ├── assets ├── ReNamed-Banner.svg └── Renamed-Logo.svg └── main.c /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://www.paypal.com/donate/?hosted_button_id=PJ962PFZ9JZHQ"] 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **Expected behavior** 14 | A clear and concise description of what you expected to happen. 15 | 16 | **Screenshots** 17 | If applicable, add screenshots to help explain your problem. 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | renamed.bluee.dev -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Renamed Banner 2 |

3 | 4 | GitHub Issues 5 | 6 | GitHub repo size 7 | GitHub last commit 8 | 9 | GitHub Release 10 | 11 | 12 | GitHub Sponsors 13 | 14 |

15 | 16 | # ReNamed 17 | **ReNamed** is a simple, terminal-based C tool that helps you automatically rename and organize episodes of TV shows — including specials — with clean, consistent filenames. 18 | 19 | ## 💡 What it Does 20 | This utility scans a folder of video files (or optionally any files), detects the episode numbers using a variety of common patterns, and renames them based on a user-supplied show name. Special episodes (like OVAs, bonus content, or labeled "SP") are detected and moved into a separate `Specials/` subfolder. 21 | 22 | ## 🛠️ How to Use 23 | 1. Download the file 24 | ```bash 25 | curl -O https://raw.githubusercontent.com/Panonim/ReNamed/refs/heads/main/main.c 26 | ``` 27 | 2. Compile the program: 28 | ```bash 29 | gcc -o renamed main.c 30 | ``` 31 | 3. Run it: 32 | ```bash 33 | ./renamed 34 | ``` 35 | 36 | 4. Follow the prompts: 37 | - Enter the show name (e.g., `Attack on Titan`) 38 | - Enter the path to the folder with episodes 39 | - Review the renaming plan 40 | - Confirm whether to proceed 41 | 42 | **Optionally put it inside /usr/local/bin to use it anywhere** 43 | 44 | ## ⚙️ Options 45 | You can use the following command-line flags: 46 | 47 | - `-v` Show version info 48 | - `-h` Show usage instructions 49 | - `-f` Force mode – includes *all* files, not just video formats (`.mp4`, `.mkv`, `.avi`) 50 | - `-p ` Specify custom output path 51 | - `-k` Keep original files (copy instead of rename) 52 | - `-d` Dry run mode - show what would happen without making changes 53 | - `--log[=file]` Create log file (default: renamed_log.txt) 54 | - `--pattern=` Specify custom regex pattern for episode detection 55 | 56 | Examples: 57 | ```bash 58 | # Force include all file types 59 | ./renamed -f 60 | 61 | # Create a log file of all operations 62 | ./renamed --log 63 | 64 | # Use a custom pattern for episode detection 65 | ./renamed --pattern='Season (\d+)-Episode (\d+)' 66 | 67 | # Combination of options 68 | ./renamed -k -f --log -p /path/to/output 69 | ``` 70 | 71 | ## 🧠 Features 72 | - Detects and extracts episode numbers from various common naming styles 73 | - Groups and handles specials (e.g., OVA, SP, Bonus) separately 74 | - Skips renaming if the episode number can't be detected 75 | - Shows a full preview of all renames before making changes 76 | - Interactive confirmation step before any file is renamed 77 | - Optionally works on *any* file type with `-f` 78 | - Dry run mode to preview changes without modifying files 79 | - Detailed logging of all operations for troubleshooting 80 | - Custom regex pattern support for specialized naming schemes 81 | 82 | ## 📜 Logging 83 | When using the `--log` option, ReNamed creates a detailed log file that includes: 84 | - Session start and end timestamps 85 | - All operations performed (rename/copy) 86 | - Success or failure status of each operation 87 | - Warnings and error messages 88 | 89 | This is especially useful for batch operations or when troubleshooting issues. 90 | 91 | ## 🔍 Custom Patterns 92 | The `--pattern` option allows you to specify your own regular expression for detecting episode numbers, which is useful for shows with unconventional naming. The pattern should include at least one capture group for the episode number. 93 | 94 | Examples: 95 | ```bash 96 | # For filenames like "Show.S01E05.mp4" 97 | ./renamed --pattern='S[0-9]+E([0-9]+)' 98 | 99 | # For filenames with season and episode like "Show.S01-E05.mp4" 100 | # (uses the second capture group) 101 | ./renamed --pattern='S([0-9]+)-E([0-9]+)' 102 | ``` 103 | 104 | ## 📂 Example 105 | Say you have: 106 | ``` 107 | Attack_on_Titan_E01.mkv 108 | Attack_on_Titan_Special_01.mp4 109 | Attack_on_Titan_E02.mkv 110 | ``` 111 | After running the tool, the folder becomes: 112 | ``` 113 | Attack on Titan - 01.mkv 114 | Attack on Titan - 02.mkv 115 | Specials/ 116 | Attack on Titan - 01 - Special.mp4 117 | ``` 118 | 119 |
120 |

121 | 122 | 123 | 124 | 125 | Star History Chart 126 | 127 | 128 |

129 | 130 | © 2025 Artur Flis. All Rights Reserved. 131 | -------------------------------------------------------------------------------- /assets/ReNamed-Banner.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /assets/Renamed-Logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | /* Program constants */ 14 | #define MAX_PATH 1024 15 | #define MAX_FILES 1000 16 | #define VERSION "a.2" 17 | #define REPO_URL "https://github.com/Panonim/ReNamed" 18 | #define DEFAULT_LOG_FILE "renamed_log.txt" 19 | #define MAX_PATTERN_LENGTH 256 20 | 21 | /* File entry structure to store file information */ 22 | typedef struct { 23 | char original_name[MAX_PATH]; 24 | char new_name[MAX_PATH]; 25 | int episode_number; 26 | int is_special; 27 | } FileEntry; 28 | 29 | /* Global configuration */ 30 | typedef struct { 31 | int force_mode; /* Force renaming of all file types */ 32 | int keep_originals; /* Keep original files (create backups) */ 33 | int dry_run; /* Dry run mode - don't actually rename files */ 34 | int use_log; /* Create log file */ 35 | int use_custom_pattern; /* Use custom regex pattern */ 36 | char output_path[MAX_PATH]; /* Custom output path */ 37 | char log_file[MAX_PATH]; /* Log file path */ 38 | char custom_pattern[MAX_PATTERN_LENGTH]; /* Custom regex pattern */ 39 | } ProgramConfig; 40 | 41 | /* Get file extension from filename */ 42 | const char *get_file_extension(const char *filename) { 43 | const char *dot = strrchr(filename, '.'); 44 | if (!dot || dot == filename) return ""; 45 | return dot; 46 | } 47 | 48 | /* Check if the file is a special episode based on filename patterns */ 49 | int is_special_episode(const char *filename) { 50 | regex_t regex; 51 | int result = 0; 52 | 53 | /* Patterns to identify special episodes */ 54 | const char *patterns[] = { 55 | "[Ss]pecial", 56 | "SP[0-9]+", 57 | "OVA", 58 | "Extra", 59 | "Bonus" 60 | }; 61 | 62 | for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); i++) { 63 | if (regcomp(®ex, patterns[i], REG_EXTENDED | REG_ICASE) != 0) { 64 | continue; 65 | } 66 | 67 | if (regexec(®ex, filename, 0, NULL, 0) == 0) { 68 | result = 1; 69 | regfree(®ex); 70 | break; 71 | } 72 | regfree(®ex); 73 | } 74 | 75 | return result; 76 | } 77 | 78 | /* Extract episode number using a custom pattern */ 79 | int extract_episode_number_custom(const char *filename, const char *pattern) { 80 | regex_t regex; 81 | regmatch_t matches[3]; /* Up to 2 capture groups + the full match */ 82 | char episode_str[10] = {0}; 83 | int episode_num = 0; 84 | 85 | if (regcomp(®ex, pattern, REG_EXTENDED) != 0) { 86 | printf("Error compiling custom pattern: %s\n", pattern); 87 | return 0; 88 | } 89 | 90 | if (regexec(®ex, filename, 3, matches, 0) == 0) { 91 | /* If we have two capture groups, assume it's Season-Episode format */ 92 | if (matches[2].rm_so != -1) { 93 | int length = matches[2].rm_eo - matches[2].rm_so; 94 | if (length < sizeof(episode_str)) { 95 | strncpy(episode_str, filename + matches[2].rm_so, length); 96 | episode_str[length] = '\0'; 97 | episode_num = atoi(episode_str); 98 | } 99 | } 100 | /* Otherwise use the first capture group */ 101 | else if (matches[1].rm_so != -1) { 102 | int length = matches[1].rm_eo - matches[1].rm_so; 103 | if (length < sizeof(episode_str)) { 104 | strncpy(episode_str, filename + matches[1].rm_so, length); 105 | episode_str[length] = '\0'; 106 | episode_num = atoi(episode_str); 107 | } 108 | } 109 | } 110 | 111 | regfree(®ex); 112 | return episode_num; 113 | } 114 | 115 | /* Extract episode number from various filename formats */ 116 | int extract_episode_number(const char *filename) { 117 | regex_t regex; 118 | regmatch_t matches[2]; 119 | char episode_str[10] = {0}; 120 | 121 | /* Common episode number patterns */ 122 | const char *patterns[] = { 123 | "Episode[ ]*([0-9]{1,3})", /* Episode 1, Episode 12 */ 124 | "Ep[ ]*([0-9]{1,3})", /* Ep 1, Ep12 */ 125 | "E([0-9]{1,3})([^0-9]|$)", /* E01, E12 */ 126 | "-[ ]*([0-9]{1,3})([^0-9]|$)", /* - 01, -12 */ 127 | "S[0-9]+[ ]*-[ ]*([0-9]{1,3})", /* S2 - 10 */ 128 | "S[0-9]+[ ]+([0-9]{1,3})", /* S2 08 */ 129 | "SP[ ]*([0-9]{1,3})", /* SP01, SP 3 (for specials) */ 130 | " ([0-9]{1,2})[^0-9]" /* Fallback: isolated numbers */ 131 | }; 132 | 133 | /* Try each pattern until we find a match */ 134 | for (int i = 0; i < sizeof(patterns) / sizeof(patterns[0]); i++) { 135 | if (regcomp(®ex, patterns[i], REG_EXTENDED) != 0) { 136 | continue; 137 | } 138 | 139 | if (regexec(®ex, filename, 2, matches, 0) == 0) { 140 | int length = matches[1].rm_eo - matches[1].rm_so; 141 | if (length < sizeof(episode_str)) { 142 | strncpy(episode_str, filename + matches[1].rm_so, length); 143 | episode_str[length] = '\0'; 144 | regfree(®ex); 145 | 146 | /* Pad single digits with leading zero */ 147 | if (strlen(episode_str) == 1) { 148 | char padded_episode_str[3] = {'0', episode_str[0], '\0'}; 149 | return atoi(padded_episode_str); 150 | } 151 | return atoi(episode_str); 152 | } 153 | } 154 | regfree(®ex); 155 | } 156 | 157 | /* Fallback: look for isolated 2-digit numbers */ 158 | for (size_t i = 0; i < strlen(filename) - 1; i++) { 159 | if (isdigit(filename[i]) && isdigit(filename[i + 1])) { 160 | /* Make sure it's not part of a larger number */ 161 | if ((i == 0 || !isdigit(filename[i - 1])) && 162 | (i + 2 >= strlen(filename) || !isdigit(filename[i + 2]))) { 163 | char num[3] = {filename[i], filename[i + 1], '\0'}; 164 | return atoi(num); 165 | } 166 | } 167 | } 168 | return 0; /* No episode number found */ 169 | } 170 | 171 | /* Create directory if it doesn't exist */ 172 | int create_directory(const char *path) { 173 | struct stat st = {0}; 174 | if (stat(path, &st) == -1) { 175 | #ifdef _WIN32 176 | if (mkdir(path) != 0) { 177 | printf("Error creating directory '%s': %s\n", path, strerror(errno)); 178 | return 0; 179 | } 180 | #else 181 | if (mkdir(path, 0755) != 0) { 182 | printf("Error creating directory '%s': %s\n", path, strerror(errno)); 183 | return 0; 184 | } 185 | #endif 186 | return 1; 187 | } 188 | return 1; /* Directory already exists */ 189 | } 190 | 191 | /* Copy a file from source to destination */ 192 | int copy_file(const char *source, const char *destination) { 193 | FILE *src, *dst; 194 | char buffer[4096]; 195 | size_t bytes_read; 196 | 197 | src = fopen(source, "rb"); 198 | if (!src) { 199 | printf("Error opening source file '%s': %s\n", source, strerror(errno)); 200 | return 0; 201 | } 202 | 203 | dst = fopen(destination, "wb"); 204 | if (!dst) { 205 | printf("Error opening destination file '%s': %s\n", destination, strerror(errno)); 206 | fclose(src); 207 | return 0; 208 | } 209 | 210 | while ((bytes_read = fread(buffer, 1, sizeof(buffer), src)) > 0) { 211 | if (fwrite(buffer, 1, bytes_read, dst) != bytes_read) { 212 | printf("Error writing to destination file '%s': %s\n", destination, strerror(errno)); 213 | fclose(src); 214 | fclose(dst); 215 | return 0; 216 | } 217 | } 218 | 219 | fclose(src); 220 | fclose(dst); 221 | return 1; 222 | } 223 | 224 | /* Log operation to file */ 225 | void log_operation(FILE *log_file, const char *action, const char *old_path, const char *new_path, int success) { 226 | time_t now; 227 | struct tm *timeinfo; 228 | char timestamp[20]; 229 | 230 | time(&now); 231 | timeinfo = localtime(&now); 232 | strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", timeinfo); 233 | 234 | fprintf(log_file, "[%s] %s: %s -> %s [%s]\n", 235 | timestamp, 236 | action, 237 | old_path, 238 | new_path, 239 | success ? "SUCCESS" : "FAILED"); 240 | } 241 | 242 | /* Compare function for sorting files */ 243 | int compare_files(const void *a, const void *b) { 244 | FileEntry *fileA = (FileEntry *)a; 245 | FileEntry *fileB = (FileEntry *)b; 246 | 247 | /* Group regular episodes before specials */ 248 | if (fileA->is_special != fileB->is_special) { 249 | return fileA->is_special - fileB->is_special; 250 | } 251 | 252 | /* Sort by episode number */ 253 | return fileA->episode_number - fileB->episode_number; 254 | } 255 | 256 | /* Display version information */ 257 | void print_version() { 258 | printf("ReNamed - Automatic Episode Renamer v%s\n", VERSION); 259 | printf("Repository: %s\n", REPO_URL); 260 | printf("\nA simple tool to rename and organize TV show episodes.\n"); 261 | } 262 | 263 | /* Display usage information */ 264 | void print_usage(char *program_name) { 265 | printf("Usage: %s [OPTIONS]\n\n", program_name); 266 | printf("Options:\n"); 267 | printf(" -v Display version information\n"); 268 | printf(" -h Display this help message\n"); 269 | printf(" -f Force renaming of all file types (not just video files)\n"); 270 | printf(" -k Keep original files\n"); 271 | printf(" -d Dry run mode (only show what would happen, don't rename files)\n"); 272 | printf(" -p Specify custom output path for renamed files\n"); 273 | printf(" --log[=file] Create log file (default: renamed_log.txt)\n"); 274 | printf(" --pattern= Specify custom regex pattern for episode detection\n"); 275 | printf(" Example: --pattern='Season (\\d+)-Episode (\\d+)'\n\n"); 276 | printf("If no options are provided, the program runs in interactive mode.\n"); 277 | } 278 | 279 | /* Check if a file is a video file */ 280 | int is_video_file(const char *extension) { 281 | return (strcasecmp(extension, ".mp4") == 0 || 282 | strcasecmp(extension, ".mkv") == 0 || 283 | strcasecmp(extension, ".avi") == 0); 284 | } 285 | 286 | int main(int argc, char *argv[]) { 287 | ProgramConfig config = {0}; /* Initialize config with defaults */ 288 | int opt; 289 | int option_index = 0; 290 | 291 | /* Default log file name */ 292 | strcpy(config.log_file, DEFAULT_LOG_FILE); 293 | 294 | /* Define long options */ 295 | static struct option long_options[] = { 296 | {"log", optional_argument, 0, 'l' }, 297 | {"pattern", required_argument, 0, 'r' }, 298 | {0, 0, 0, 0 } 299 | }; 300 | 301 | /* Use getopt for command line parsing */ 302 | while ((opt = getopt_long(argc, argv, "vhfkdp:", long_options, &option_index)) != -1) { 303 | switch (opt) { 304 | case 'v': 305 | print_version(); 306 | return 0; 307 | case 'h': 308 | print_usage(argv[0]); 309 | return 0; 310 | case 'f': 311 | config.force_mode = 1; 312 | break; 313 | case 'k': 314 | config.keep_originals = 1; 315 | break; 316 | case 'd': 317 | config.dry_run = 1; 318 | break; 319 | case 'p': 320 | strncpy(config.output_path, optarg, MAX_PATH - 1); 321 | config.output_path[MAX_PATH - 1] = '\0'; 322 | break; 323 | case 'l': /* --log option */ 324 | config.use_log = 1; 325 | if (optarg) { 326 | strncpy(config.log_file, optarg, MAX_PATH - 1); 327 | config.log_file[MAX_PATH - 1] = '\0'; 328 | } 329 | break; 330 | case 'r': /* --pattern option */ 331 | config.use_custom_pattern = 1; 332 | strncpy(config.custom_pattern, optarg, MAX_PATTERN_LENGTH - 1); 333 | config.custom_pattern[MAX_PATTERN_LENGTH - 1] = '\0'; 334 | break; 335 | default: 336 | printf("Unknown option: %c\n", opt); 337 | print_usage(argv[0]); 338 | return 1; 339 | } 340 | } 341 | 342 | /* Parse non-option arguments for --log and --pattern */ 343 | for (int i = optind; i < argc; i++) { 344 | if (strncmp(argv[i], "--log", 5) == 0) { 345 | config.use_log = 1; 346 | char *equals = strchr(argv[i], '='); 347 | if (equals && *(equals + 1)) { 348 | strncpy(config.log_file, equals + 1, MAX_PATH - 1); 349 | config.log_file[MAX_PATH - 1] = '\0'; 350 | } 351 | } else if (strncmp(argv[i], "--pattern=", 10) == 0) { 352 | config.use_custom_pattern = 1; 353 | strncpy(config.custom_pattern, argv[i] + 10, MAX_PATTERN_LENGTH - 1); 354 | config.custom_pattern[MAX_PATTERN_LENGTH - 1] = '\0'; 355 | } 356 | } 357 | 358 | char show_name[MAX_PATH]; 359 | char folder_path[MAX_PATH]; 360 | char destination_path[MAX_PATH] = {0}; 361 | char specials_path[MAX_PATH]; 362 | char confirm[10]; 363 | FileEntry files[MAX_FILES]; 364 | int file_count = 0; 365 | DIR *dir; 366 | struct dirent *entry; 367 | FILE *log_fp = NULL; 368 | 369 | /* Open log file if logging is enabled */ 370 | if (config.use_log) { 371 | log_fp = fopen(config.log_file, "a"); 372 | if (!log_fp) { 373 | printf("Warning: Could not open log file '%s': %s\n", config.log_file, strerror(errno)); 374 | printf("Continuing without logging.\n"); 375 | config.use_log = 0; 376 | } else { 377 | /* Write header to log file */ 378 | time_t now; 379 | struct tm *timeinfo; 380 | char timestamp[20]; 381 | 382 | time(&now); 383 | timeinfo = localtime(&now); 384 | strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", timeinfo); 385 | 386 | fprintf(log_fp, "\n----- ReNamed Session Started at %s -----\n", timestamp); 387 | if (config.dry_run) { 388 | fprintf(log_fp, "[INFO] Running in DRY RUN mode - no actual changes made\n"); 389 | } 390 | } 391 | } 392 | 393 | /* Get show name from user */ 394 | printf("Enter show name: "); 395 | if (fgets(show_name, sizeof(show_name), stdin) == NULL) { 396 | printf("Error reading input.\n"); 397 | if (log_fp) fclose(log_fp); 398 | return 1; 399 | } 400 | show_name[strcspn(show_name, "\n")] = 0; /* Remove newline */ 401 | 402 | if (strlen(show_name) == 0) { 403 | printf("Show name cannot be empty.\n"); 404 | if (log_fp) fclose(log_fp); 405 | return 1; 406 | } 407 | 408 | /* Get folder path from user */ 409 | printf("Enter folder path with source files: "); 410 | if (fgets(folder_path, sizeof(folder_path), stdin) == NULL) { 411 | printf("Error reading input.\n"); 412 | if (log_fp) fclose(log_fp); 413 | return 1; 414 | } 415 | folder_path[strcspn(folder_path, "\n")] = 0; /* Remove newline */ 416 | 417 | if (strlen(folder_path) == 0) { 418 | printf("Folder path cannot be empty.\n"); 419 | if (log_fp) fclose(log_fp); 420 | return 1; 421 | } 422 | 423 | /* If output path not specified via command line, use source path or ask user */ 424 | if (strlen(config.output_path) == 0) { 425 | if (config.keep_originals) { 426 | /* Ask for destination path when keeping originals */ 427 | printf("Enter destination folder path for renamed files: "); 428 | if (fgets(destination_path, sizeof(destination_path), stdin) == NULL) { 429 | printf("Error reading input.\n"); 430 | if (log_fp) fclose(log_fp); 431 | return 1; 432 | } 433 | destination_path[strcspn(destination_path, "\n")] = 0; /* Remove newline */ 434 | 435 | if (strlen(destination_path) == 0) { 436 | printf("Destination path cannot be empty when using backup mode.\n"); 437 | if (log_fp) fclose(log_fp); 438 | return 1; 439 | } 440 | } else { 441 | /* Use source folder as destination (for in-place renaming) */ 442 | strncpy(destination_path, folder_path, MAX_PATH - 1); 443 | destination_path[MAX_PATH - 1] = '\0'; 444 | } 445 | } else { 446 | /* Use path provided from command line */ 447 | strncpy(destination_path, config.output_path, MAX_PATH - 1); 448 | destination_path[MAX_PATH - 1] = '\0'; 449 | } 450 | 451 | /* Log operation details */ 452 | if (log_fp) { 453 | fprintf(log_fp, "[INFO] Show name: '%s'\n", show_name); 454 | fprintf(log_fp, "[INFO] Source folder: '%s'\n", folder_path); 455 | fprintf(log_fp, "[INFO] Destination folder: '%s'\n", destination_path); 456 | if (config.use_custom_pattern) { 457 | fprintf(log_fp, "[INFO] Using custom pattern: '%s'\n", config.custom_pattern); 458 | } 459 | } 460 | 461 | /* Create destination directory if it doesn't exist (even in dry run, for planning) */ 462 | if (!config.dry_run && !create_directory(destination_path)) { 463 | printf("Error: Failed to create destination directory '%s'\n", destination_path); 464 | if (log_fp) fclose(log_fp); 465 | return 1; 466 | } 467 | 468 | /* Create path for specials directory */ 469 | snprintf(specials_path, sizeof(specials_path), "%s/Specials", destination_path); 470 | 471 | /* Try to open directory */ 472 | dir = opendir(folder_path); 473 | if (dir == NULL) { 474 | printf("Error: Unable to open directory '%s': %s\n", folder_path, strerror(errno)); 475 | if (log_fp) fclose(log_fp); 476 | return 1; 477 | } 478 | 479 | /* Scan directory for files */ 480 | if (config.force_mode) { 481 | printf("Scanning directory for all files (force mode)...\n"); 482 | } else { 483 | printf("Scanning directory for video files...\n"); 484 | } 485 | 486 | while ((entry = readdir(dir)) != NULL && file_count < MAX_FILES) { 487 | /* Skip . and .. directories */ 488 | if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) 489 | continue; 490 | 491 | /* Skip directories */ 492 | char full_path[MAX_PATH]; 493 | snprintf(full_path, sizeof(full_path), "%s/%s", folder_path, entry->d_name); 494 | 495 | struct stat path_stat; 496 | if (stat(full_path, &path_stat) != 0) { 497 | printf("Warning: Cannot get stats for '%s': %s\n", entry->d_name, strerror(errno)); 498 | continue; 499 | } 500 | 501 | if (!S_ISREG(path_stat.st_mode)) 502 | continue; 503 | 504 | /* Get file extension */ 505 | const char *extension = get_file_extension(entry->d_name); 506 | 507 | /* Skip non-video files unless force mode is enabled */ 508 | if (!config.force_mode && !is_video_file(extension)) 509 | continue; 510 | 511 | /* Check if this is a special episode */ 512 | int special = is_special_episode(entry->d_name); 513 | 514 | /* Extract episode number using either custom or default patterns */ 515 | int episode_num; 516 | if (config.use_custom_pattern) { 517 | episode_num = extract_episode_number_custom(entry->d_name, config.custom_pattern); 518 | } else { 519 | episode_num = extract_episode_number(entry->d_name); 520 | } 521 | 522 | if (episode_num == 0) { 523 | printf("Warning: No episode number found in '%s', skipping.\n", entry->d_name); 524 | if (log_fp) { 525 | fprintf(log_fp, "[WARNING] No episode number found in '%s', skipping.\n", entry->d_name); 526 | } 527 | continue; 528 | } 529 | 530 | /* Store file information */ 531 | strcpy(files[file_count].original_name, entry->d_name); 532 | files[file_count].episode_number = episode_num; 533 | files[file_count].is_special = special; 534 | 535 | /* Generate new filename based on type */ 536 | if (special) { 537 | snprintf(files[file_count].new_name, MAX_PATH, "%s - %02d - Special%s", 538 | show_name, episode_num, extension); 539 | } else { 540 | snprintf(files[file_count].new_name, MAX_PATH, "%s - %02d%s", 541 | show_name, episode_num, extension); 542 | } 543 | 544 | file_count++; 545 | } 546 | 547 | closedir(dir); 548 | 549 | if (file_count == 0) { 550 | printf("No suitable files found in the directory.\n"); 551 | if (log_fp) { 552 | fprintf(log_fp, "[INFO] No suitable files found in the directory.\n"); 553 | fclose(log_fp); 554 | } 555 | return 1; 556 | } 557 | 558 | /* Sort files by episode number */ 559 | qsort(files, file_count, sizeof(FileEntry), compare_files); 560 | 561 | /* Display the rename plan */ 562 | printf("\nFound %d files. Rename Plan%s:\n", file_count, config.dry_run ? " (DRY RUN)" : ""); 563 | 564 | /* Show operation mode */ 565 | if (config.dry_run) { 566 | printf("Operation mode: DRY RUN - no actual changes will be made\n"); 567 | } else if (config.keep_originals) { 568 | printf("Operation mode: Copying files (keeping originals)\n"); 569 | } else { 570 | printf("Operation mode: Moving/renaming files\n"); 571 | } 572 | printf("Destination directory: %s\n", destination_path); 573 | if (config.use_log) { 574 | printf("Logging enabled: '%s'\n", config.log_file); 575 | } 576 | if (config.use_custom_pattern) { 577 | printf("Using custom pattern: '%s'\n", config.custom_pattern); 578 | } 579 | 580 | printf("\n%-70s -> %s\n", "Original Filename", "New Filename"); 581 | printf("--------------------------------------------------------------------------------\n"); 582 | 583 | /* Check if any special episodes exist */ 584 | int has_special_episodes = 0; 585 | for (int i = 0; i < file_count; i++) { 586 | if (files[i].is_special) { 587 | has_special_episodes = 1; 588 | break; 589 | } 590 | } 591 | 592 | for (int i = 0; i < file_count; i++) { 593 | char orig_truncated[71] = {0}; 594 | strncpy(orig_truncated, files[i].original_name, 70); 595 | if (strlen(files[i].original_name) > 70) { 596 | strcpy(orig_truncated + 67, "..."); 597 | } 598 | 599 | if (files[i].is_special) { 600 | printf("%-70s -> Specials/%s (SPECIAL)\n", orig_truncated, files[i].new_name); 601 | } else { 602 | printf("%-70s -> %s\n", orig_truncated, files[i].new_name); 603 | } 604 | } 605 | 606 | /* Skip confirmation in dry run mode */ 607 | if (config.dry_run) { 608 | printf("\nDRY RUN completed. No files were modified.\n"); 609 | if (log_fp) { 610 | fprintf(log_fp, "[INFO] DRY RUN completed. No files were modified.\n"); 611 | fprintf(log_fp, "----- ReNamed Session Ended -----\n\n"); 612 | fclose(log_fp); 613 | } 614 | return 0; 615 | } 616 | 617 | /* Ask for confirmation */ 618 | printf("\nContinue with %s? (yes/no): ", config.keep_originals ? "copying" : "renaming"); 619 | if (fgets(confirm, sizeof(confirm), stdin) == NULL) { 620 | printf("Error reading input.\n"); 621 | if (log_fp) { 622 | fprintf(log_fp, "[ERROR] Failed to read user confirmation.\n"); 623 | fclose(log_fp); 624 | } 625 | return 1; 626 | } 627 | 628 | if (strncasecmp(confirm, "yes", 3) == 0 || strncasecmp(confirm, "y", 1) == 0) { 629 | /* Create destination directory if different from source */ 630 | if (strcmp(folder_path, destination_path) != 0) { 631 | if (!create_directory(destination_path)) { 632 | printf("Error: Failed to create destination directory '%s'\n", destination_path); 633 | if (log_fp) { 634 | fprintf(log_fp, "[ERROR] Failed to create destination directory '%s'\n", destination_path); 635 | fclose(log_fp); 636 | } 637 | return 1; 638 | } 639 | } 640 | 641 | /* Create specials directory only if special episodes exist */ 642 | if (has_special_episodes) { 643 | if (create_directory(specials_path)) { 644 | printf("Created 'Specials' directory in '%s'.\n", destination_path); 645 | if (log_fp) { 646 | fprintf(log_fp, "[INFO] Created 'Specials' directory in '%s'.\n", destination_path); 647 | } 648 | } 649 | } 650 | 651 | /* Perform renaming/copying */ 652 | int success_count = 0; 653 | int special_count = 0; 654 | int regular_count = 0; 655 | 656 | for (int i = 0; i < file_count; i++) { 657 | char old_path[MAX_PATH]; 658 | char new_path[MAX_PATH]; 659 | 660 | snprintf(old_path, sizeof(old_path), "%s/%s", folder_path, files[i].original_name); 661 | 662 | if (files[i].is_special) { 663 | snprintf(new_path, sizeof(new_path), "%s/%s", specials_path, files[i].new_name); 664 | special_count++; 665 | } else { 666 | snprintf(new_path, sizeof(new_path), "%s/%s", destination_path, files[i].new_name); 667 | regular_count++; 668 | } 669 | 670 | if (config.keep_originals) { 671 | /* Copy the file instead of renaming */ 672 | int success = copy_file(old_path, new_path); 673 | if (success) { 674 | success_count++; 675 | printf("Copied '%s' to '%s'\n", files[i].original_name, new_path); 676 | if (log_fp) { 677 | log_operation(log_fp, "COPY", old_path, new_path, 1); 678 | } 679 | } else { 680 | printf("Error copying '%s' to '%s'\n", files[i].original_name, new_path); 681 | if (log_fp) { 682 | log_operation(log_fp, "COPY", old_path, new_path, 0); 683 | } 684 | } 685 | } else { 686 | /* Rename/move the file */ 687 | if (rename(old_path, new_path) == 0) { 688 | success_count++; 689 | printf("Renamed '%s' to '%s'\n", files[i].original_name, files[i].new_name); 690 | if (log_fp) { 691 | log_operation(log_fp, "RENAME", old_path, new_path, 1); 692 | } 693 | } else { 694 | printf("Error renaming '%s' to '%s': %s\n", 695 | files[i].original_name, 696 | files[i].new_name, 697 | strerror(errno)); 698 | if (log_fp) { 699 | log_operation(log_fp, "RENAME", old_path, new_path, 0); 700 | } 701 | } 702 | } 703 | } 704 | 705 | printf("\nOperation complete!\n"); 706 | printf("- %d of %d files successfully %s\n", 707 | success_count, file_count, 708 | config.keep_originals ? "copied" : "renamed"); 709 | printf("- %d regular episodes\n", regular_count); 710 | printf("- %d special episodes", special_count); 711 | if (special_count > 0) { 712 | printf(" moved to Specials folder"); 713 | } 714 | printf("\n"); 715 | 716 | if (log_fp) { 717 | fprintf(log_fp, "[INFO] Operation complete! %d of %d files successfully %s.\n", 718 | success_count, file_count, config.keep_originals ? "copied" : "renamed"); 719 | fprintf(log_fp, "[INFO] %d regular episodes, %d special episodes.\n", 720 | regular_count, special_count); 721 | fprintf(log_fp, "----- ReNamed Session Ended -----\n\n"); 722 | } 723 | } else { 724 | printf("Operation cancelled.\n"); 725 | if (log_fp) { 726 | fprintf(log_fp, "[INFO] Operation cancelled by user.\n"); 727 | fprintf(log_fp, "----- ReNamed Session Ended -----\n\n"); 728 | } 729 | } 730 | 731 | if (log_fp) { 732 | fclose(log_fp); 733 | } 734 | 735 | return 0; 736 | } 737 | --------------------------------------------------------------------------------