changeset 813:b0cd28b6c9f3

Add new utility functions.
author Matti Hamalainen <ccr@tnsp.org>
date Fri, 16 May 2014 15:17:48 +0300
parents 1e5cf1144f36
children 5753d7f24106
files src/dmlib.h src/dmstring.c
diffstat 2 files changed, 47 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/src/dmlib.h	Fri May 16 03:22:39 2014 +0300
+++ b/src/dmlib.h	Fri May 16 15:17:48 2014 +0300
@@ -63,6 +63,9 @@
     DMERR_COMPRESSION,
 };
 
+// Directory/path separator stuff
+#define DM_DIR_SEPARATOR     '/'
+
 
 // Resource management defines
 #define DMRES_NAME_LEN  32
@@ -399,6 +402,9 @@
 char *     dm_strdup_vprintf(const char *, va_list);
 char *     dm_strdup_printf(const char *, ...);
 
+char *     dm_basefilename(const char *filename);
+char *     dm_strdup_fext(const char *filename, const char *fmt);
+
 
 /* Mutexes
  */
--- a/src/dmstring.c	Fri May 16 03:22:39 2014 +0300
+++ b/src/dmstring.c	Fri May 16 15:17:48 2014 +0300
@@ -1,6 +1,47 @@
 #include "dmlib.h"
 #include <stdarg.h>
 
+
+/* Returns the filename and path without the last filename extension,
+ * E.g. everything before the last '.', if any.
+ */
+char *dm_basefilename(const char *filename)
+{
+    char *tmp, *fext;
+
+    if (filename == NULL ||
+        (tmp = dm_strdup(filename)) == NULL)
+        return NULL;
+
+    if ((fext = strrchr(tmp, '.')) != NULL)
+    {
+        char *fpath = strrchr(tmp, DM_DIR_SEPARATOR);
+        if (fpath == NULL || (fpath != NULL && fext > fpath))
+            *fext = 0;
+    }
+
+    return tmp;
+}
+
+
+/* Replace filename extension based on format pattern.
+ * Usage: res = dm_strdup_fext(orig_filename, "foo_%s.cmp");
+ */
+char *dm_strdup_fext(const char *filename, const char *fmt)
+{
+    char *result, *tmp;
+
+    if ((tmp = dm_basefilename(filename)) == NULL)
+        return NULL;
+
+    result = dm_strdup_printf(fmt, tmp);
+
+    dmFree(tmp);
+
+    return result;
+}
+
+
 /* Implementation of strdup() with a NULL check
  */
 char *dm_strdup(const char *s)