diff options
-rw-r--r-- | src/common.c | 101 | ||||
-rw-r--r-- | src/common.h | 7 |
2 files changed, 108 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c index 81f5641..55149a7 100644 --- a/src/common.c +++ b/src/common.c @@ -73,3 +73,104 @@ int itoc(int num, char* out) { return out_count; } + + +/** + * Returns the current localtime in format YYYYMMDD.HHmmss. Useful for "random" + * non-conflicting filenames. + * + * @param date Output variable for the date string. The output variable must + * have space for the date to be stored, otherwise unexpected + * behavior may occur. + */ +void get_current_date_time(char* date) { + time_t rawtime; + time(&rawtime); + struct tm* now = localtime(&rawtime); + + // Date + // Year + int year = now->tm_year + 1900; + char c_year[5]; + itoc(year, c_year); + strcpy(date, c_year); + + // Month + int mon = now->tm_mon + 1; + char c_mon[3]; + itoc(mon, c_mon); + if(mon < 10) { strcat(date, "0"); } + strcat(date, c_mon); + + // Day + int day = now->tm_mday; + char c_day[3]; + if(day < 10) { strcat(date, "0"); } + strcat(date, c_day); + + // A delimiter to make it easier for humans to read. + strcat(date, "."); + + // Time + // Hour + int hour = now->tm_hour; + char c_hour[3]; + itoc(hour, c_hour); + if(hour < 10) { strcat(date, "0"); } + strcat(date, c_hour); + + // Minute + int min = now->tm_min; + char c_min[3]; + itoc(min, c_min); + if(min < 10) { strcat(date, "0"); } + strcat(date, c_min); + + // Second + int sec = now->tm_sec; + char c_sec[3]; + itoc(sec, c_sec); + if(sec < 10) { strcat(date, "0"); } + strcat(date, c_sec); +} + + +/** + * TODO: Write this function description + * + * @return int Extension char length + */ +int get_extension(char* path, char* extension) { + int path_len = strlen(path); + // Start from the right and move left + for(int i = path_len; i > 0; i--) { + // Copy if an extension delimiter (a period) is found + if(path[i] == '.') { + int ext_len = path_len - i - 1; + strncpy(extension, &path[i+1], ext_len); + return ext_len; + } + } + return -1; +} + + +/** + * Yup, wrote my own. + * TODO: Make this work with escaped path delimiters + * TODO: Write this function description + * + * @return int Basename path length + */ +int basename(char* path, char* out) { + int path_len = strlen(path); + // Start from the right and move left + for(int i = path_len; i > 0; i--) { + // Copy if an extension delimiter (a period) is found + if(path[i] == '/') { + strncpy(out, path, i); + return i; + } + } + return -1; +} diff --git a/src/common.h b/src/common.h index 89b9026..6fb5ed1 100644 --- a/src/common.h +++ b/src/common.h @@ -17,6 +17,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <time.h> #ifndef noteless_common #define noteless_common @@ -25,4 +26,10 @@ void get_user_editor(char*); int itoc(int, char*); +void get_current_date_time(char*); + +int get_extension(char*, char*); + +int basename(char*, char*); + #endif |