2 ** utils.c -- various utility routines
4 ** This code is Copyright (c) 2006, by the authors of nmh. See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
16 ** We allocate space for messages (msgs array)
17 ** this number of elements at a time.
25 mh_xmalloc(size_t size)
30 adios(NULL, "Tried to malloc 0 bytes");
32 memory = malloc(size);
34 adios(NULL, "Malloc failed");
40 ** Safely call realloc
43 mh_xrealloc(void *ptr, size_t size)
47 /* Some non-POSIX realloc()s don't cope with realloc(NULL,sz) */
49 return mh_xmalloc(size);
53 adios(NULL, "Tried to realloc 0 bytes");
55 memory = realloc(ptr, size);
57 adios(NULL, "Realloc failed");
63 ** Return the present working directory, if the current directory does not
64 ** exist, or is too long, make / the pwd.
70 static char curwd[PATH_MAX];
72 if (!getcwd(curwd, PATH_MAX)) {
73 admonish(NULL, "unable to determine working directory");
74 if (!mypath || !*mypath ||
75 (strcpy(curwd, mypath), chdir(curwd)) == -1) {
82 if ((cp = curwd + strlen(curwd) - 1) > curwd && *cp == '/') {
83 /* strip trailing slash */
91 ** add -- If "s1" is NULL, this routine just creates a
92 ** -- copy of "s2" into newly malloc'ed memory.
93 ** -- (use getcpy() instead in this case)
95 ** -- If "s1" is not NULL, then copy the concatenation
96 ** -- of "s1" and "s2" (note the order) into newly
97 ** -- malloc'ed memory. Then free "s1".
100 add(char *s2, char *s1)
103 size_t len1 = 0, len2 = 0;
110 cp = mh_xmalloc(len1 + len2 + 1);
112 /* Copy s1 and free it */
114 memcpy(cp, s1, len1);
120 memcpy(cp + len1, s2, len2);
122 /* Now NULL terminate the string */
123 cp[len1 + len2] = '\0';
131 ** Check to see if a folder exists, if not, prompt the user to create it.
134 create_folder(char *folder, int autocreate, void (*done_callback)(int))
140 if (stat(folder, &st) == -1) {
142 adios(folder, "error on folder");
143 if (autocreate == 0) {
144 /* ask before creating folder */
145 cp = concat("Create folder \"", folder, "\"? ", NULL);
149 } else if (autocreate == -1) {
150 /* do not create, so exit */
153 if (!makedir(folder))
154 adios(NULL, "unable to create folder %s", folder);
160 ** Return the number of digits in a nonnegative integer.
169 adios(NULL, "oops, num_digits called with negative value");
183 ** Append a message arg to an array of them, resizing it if necessary.
184 ** The function is written to suit the arg parsing code it was extracted
185 ** from, and will probably be changed when the other code is cleaned up.
188 app_msgarg(struct msgs_array *msgs, char *cp)
190 if(msgs->size >= msgs->max)
191 msgs->msgs = mh_xrealloc(msgs->msgs,
192 (msgs->max+=MAXMSGS)*sizeof(*msgs->msgs));
193 msgs->msgs[msgs->size++] = cp;