3 * utils.c -- various utility routines
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.
18 * We allocate space for messages (msgs array)
19 * this number of elements at a time.
27 mh_xmalloc(size_t size)
32 adios(NULL, "Tried to malloc 0 bytes");
34 memory = malloc(size);
36 adios(NULL, "Malloc failed");
45 mh_xrealloc(void *ptr, size_t size)
50 adios(NULL, "Tried to realloc 0bytes");
52 memory = realloc(ptr, size);
54 adios(NULL, "Realloc failed");
60 * Return the present working directory, if the current directory does not
61 * exist, or is too long, make / the pwd.
67 static char curwd[PATH_MAX];
69 if (!getcwd (curwd, PATH_MAX)) {
70 admonish (NULL, "unable to determine working directory");
71 if (!mypath || !*mypath
72 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
79 if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
86 * add -- If "s1" is NULL, this routine just creates a
87 * -- copy of "s2" into newly malloc'ed memory.
89 * -- If "s1" is not NULL, then copy the concatenation
90 * -- of "s1" and "s2" (note the order) into newly
91 * -- malloc'ed memory. Then free "s1".
94 add (char *s2, char *s1)
97 size_t len1 = 0, len2 = 0;
104 cp = mh_xmalloc (len1 + len2 + 1);
106 /* Copy s1 and free it */
108 memcpy (cp, s1, len1);
114 memcpy (cp + len1, s2, len2);
116 /* Now NULL terminate the string */
117 cp[len1 + len2] = '\0';
124 * Check to see if a folder exists, if not, prompt the user to create
127 void create_folder(char *folder, int autocreate, void (*done_callback)())
133 if (stat (folder, &st) == -1) {
135 adios (folder, "error on folder");
136 if (autocreate == 0) {
137 /* ask before creating folder */
138 cp = concat ("Create folder \"", folder, "\"? ", NULL);
142 } else if (autocreate == -1) {
143 /* do not create, so exit */
146 if (!makedir (folder))
147 adios (NULL, "unable to create folder %s", folder);
153 * Return the number of digits in a nonnegative integer.
162 adios (NULL, "oops, num_digits called with negative value");
176 * Append a message arg to an array of them, resizing it if necessary.
177 * The function is written to suit the arg parsing code it was extracted
178 * from, and will probably be changed when the other code is cleaned up.
181 app_msgarg(struct msgs_array *msgs, char *cp)
183 if(msgs->size >= msgs->max)
184 msgs->msgs = mh_xrealloc(msgs->msgs, (msgs->max+=MAXMSGS)*sizeof(*msgs->msgs));
185 msgs->msgs[msgs->size++] = cp;