Debian Codegraph @

src/sysutil.c

raw
1 /*
2 sysutil: generic utilities to interact with the OS (signals, paths)
3
4 copyright ?-2014 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Michael Hipp (dissected/renamed by Thomas Orgis)
7 */
8
9 #include "mpg123app.h"
10 #include <sys/stat.h>
11 #include "sysutil.h"
12
13 #include "common/debug.h"
14
15 #if 0
16 /* removed the strndup for better portability */
17 /*
18 * Allocate space for a new string containing the first
19 * "num" characters of "src". The resulting string is
20 * always zero-terminated. Returns NULL if malloc fails.
21 */
22 char *strndup (const char *src, int num)
23 {
24 char *dst;
25
26 if (!(dst = (char *) malloc(num+1)))
27 return (NULL);
28 dst[num] = '\0';
29 return (strncpy(dst, src, num));
30 }
31 #endif
32
33
34 size_t dir_length(const char *path)
35 {
36 const char * slashpos = strrchr(path, '/');
37 return (slashpos ? slashpos-path : 0);
38 }
39
40 /*
41 * Split "path" into directory and filename components.
42 *
43 * Return value is 0 if no directory was specified (i.e.
44 * "path" does not contain a '/'), OR if the directory
45 * is the same as on the previous call to this function.
46 *
47 * Return value is 1 if a directory was specified AND it
48 * is different from the previous one (if any).
49 */
50
51 int split_dir_file (const char *path, const char **dname, const char **fname)
52 {
53 static char *lastdir = NULL;
54 static size_t lastlen = 0;
55 size_t dlen = dir_length(path);
56
57 if (dlen) {
58 *fname = path + dlen + 1; // a one-byte separator is implied
59 if (lastdir && dlen == lastlen && !strncmp(lastdir, path, dlen)) {
60 /*** same as previous directory ***/
61 *dname = lastdir;
62 return 0;
63 }
64 // a temporary pointer to be able to modify the string before const
65 // Care to optimize that strdup to only copy directory part?
66 char *pre_dname = INT123_compat_strdup(path); /* , 1 + slashpos - path); */
67 *dname = pre_dname;
68 if(!(*dname)) {
69 perror("failed to allocate memory for dir name");
70 return 0;
71 }
72 pre_dname[dlen+1] = 0; // keep separator (or not?)
73 if (lastdir)
74 free (lastdir);
75 lastdir = pre_dname;
76 lastlen = dlen;
77 return 1;
78 }
79 else {
80 /*** no directory specified ***/
81 if (lastdir) {
82 free (lastdir);
83 lastdir = NULL;
84 };
85 lastlen = 0;
86 *dname = NULL;
87 *fname = path;
88 return 0;
89 }
90 }