2120b84541cb77ee7d3933c00e07f6823ec90d5d
[mmh] / sbr / utils.c
1
2 /*
3  * utils.c -- various utility routines
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2006, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/utils.h>
14 #include <stdlib.h>
15
16 /*
17  * Safely call malloc
18  */
19 void *
20 mh_xmalloc(size_t size)
21 {
22     void *memory;
23
24     if (size == 0)
25         adios(NULL, "Tried to malloc 0 bytes");
26
27     memory = malloc(size);
28     if (!memory)
29         adios(NULL, "Malloc failed");
30
31     return memory;
32 }
33
34 /*
35  * Safely call realloc
36  */
37 void *
38 mh_xrealloc(void *ptr, size_t size)
39 {
40     void *memory;
41
42     if (size == 0)
43         adios(NULL, "Tried to realloc 0bytes");
44
45     memory = realloc(ptr, size);
46     if (!memory)
47         adios(NULL, "Realloc failed");
48
49     return memory;
50 }
51
52 /*
53  * Return the present working directory, if the current directory does not
54  * exist, or is too long, make / the pwd.
55  */
56 char *
57 pwd(void)
58 {
59     register char *cp;
60     static char curwd[PATH_MAX];
61
62     if (!getcwd (curwd, PATH_MAX)) {
63         admonish (NULL, "unable to determine working directory");
64         if (!mypath || !*mypath
65                 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
66             strcpy (curwd, "/");
67             chdir (curwd);
68         }
69         return curwd;
70     }
71
72     if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
73         *cp = '\0';
74
75     return curwd;
76 }