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.
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");
42 ** Safely call realloc
45 mh_xrealloc(void *ptr, size_t size)
49 /* Some non-POSIX realloc()s don't cope with realloc(NULL,sz) */
51 return mh_xmalloc(size);
55 adios(NULL, "Tried to realloc 0 bytes");
57 memory = realloc(ptr, size);
59 adios(NULL, "Realloc failed");
65 ** Return the present working directory, if the current directory does not
66 ** exist, or is too long, make / the pwd.
72 static char curwd[PATH_MAX];
74 if (!getcwd(curwd, PATH_MAX)) {
75 admonish(NULL, "unable to determine working directory");
76 if (!mypath || !*mypath ||
77 (strcpy(curwd, mypath), chdir(curwd)) == -1) {
84 if ((cp = curwd + strlen(curwd) - 1) > curwd && *cp == '/') {
85 /* strip trailing slash */
93 ** add -- If "s1" is NULL, this routine just creates a
94 ** -- copy of "s2" into newly malloc'ed memory.
95 ** -- (use getcpy() instead in this case)
97 ** -- If "s1" is not NULL, then copy the concatenation
98 ** -- of "s1" and "s2" (note the order) into newly
99 ** -- malloc'ed memory. Then free "s1".
102 add(char *s2, char *s1)
105 size_t len1 = 0, len2 = 0;
112 cp = mh_xmalloc(len1 + len2 + 1);
114 /* Copy s1 and free it */
116 memcpy(cp, s1, len1);
122 memcpy(cp + len1, s2, len2);
124 /* Now NULL terminate the string */
125 cp[len1 + len2] = '\0';
133 ** Check to see if a folder exists, if not, prompt the user to create it.
136 create_folder(char *folder, int autocreate, void (*done_callback)(int))
142 if (stat(folder, &st) == -1) {
144 adios(folder, "error on folder");
145 if (autocreate == 0) {
146 /* ask before creating folder */
147 cp = concat("Create folder \"", folder, "\"? ", NULL);
151 } else if (autocreate == -1) {
152 /* do not create, so exit */
155 if (!makedir(folder))
156 adios(NULL, "unable to create folder %s", folder);
162 ** Return the number of digits in a nonnegative integer.
171 adios(NULL, "oops, num_digits called with negative value");
185 ** Append a message arg to an array of them, resizing it if necessary.
186 ** The function is written to suit the arg parsing code it was extracted
187 ** from, and will probably be changed when the other code is cleaned up.
190 app_msgarg(struct msgs_array *msgs, char *cp)
192 if(msgs->size >= msgs->max)
193 msgs->msgs = mh_xrealloc(msgs->msgs,
194 (msgs->max+=MAXMSGS)*sizeof(*msgs->msgs));
195 msgs->msgs[msgs->size++] = cp;