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.
19 * We allocate space for messages (msgs array)
20 * this number of elements at a time.
28 mh_xmalloc(size_t size)
33 adios(NULL, "Tried to malloc 0 bytes");
35 memory = malloc(size);
37 adios(NULL, "Malloc failed");
46 mh_xrealloc(void *ptr, size_t size)
51 adios(NULL, "Tried to realloc 0bytes");
53 memory = realloc(ptr, size);
55 adios(NULL, "Realloc failed");
61 * Return the present working directory, if the current directory does not
62 * exist, or is too long, make / the pwd.
68 static char curwd[PATH_MAX];
70 if (!getcwd (curwd, PATH_MAX)) {
71 admonish (NULL, "unable to determine working directory");
72 if (!mypath || !*mypath
73 || (strcpy (curwd, mypath), chdir (curwd)) == -1) {
80 if ((cp = curwd + strlen (curwd) - 1) > curwd && *cp == '/')
87 * add -- If "s1" is NULL, this routine just creates a
88 * -- copy of "s2" into newly malloc'ed memory.
90 * -- If "s1" is not NULL, then copy the concatenation
91 * -- of "s1" and "s2" (note the order) into newly
92 * -- malloc'ed memory. Then free "s1".
95 add (char *s2, char *s1)
98 size_t len1 = 0, len2 = 0;
105 cp = mh_xmalloc (len1 + len2 + 1);
107 /* Copy s1 and free it */
109 memcpy (cp, s1, len1);
115 memcpy (cp + len1, s2, len2);
117 /* Now NULL terminate the string */
118 cp[len1 + len2] = '\0';
125 * Check to see if a folder exists, if not, prompt the user to create
128 void create_folder(char *folder, int autocreate, void (*done_callback)())
134 if (stat (folder, &st) == -1) {
136 adios (folder, "error on folder");
137 if (autocreate == 0) {
138 /* ask before creating folder */
139 cp = concat ("Create folder \"", folder, "\"? ", NULL);
143 } else if (autocreate == -1) {
144 /* do not create, so exit */
147 if (!makedir (folder))
148 adios (NULL, "unable to create folder %s", folder);
154 * Return the number of digits in a nonnegative integer.
163 adios (NULL, "oops, num_digits called with negative value");
177 * Append a message arg to an array of them, resizing it if necessary.
178 * The function is written to suit the arg parsing code it was extracted
179 * from, and will probably be changed when the other code is cleaned up.
182 app_msgarg(struct msgs_array *msgs, char *cp)
184 if(msgs->size >= msgs->max)
185 msgs->msgs = mh_xrealloc(msgs->msgs, (msgs->max+=MAXMSGS)*sizeof(*msgs->msgs));
186 msgs->msgs[msgs->size++] = cp;
189 /* Open a form or components file */
191 open_form(char **form, char *def)
195 if ((in = open (etcpath (*form), O_RDONLY)) == NOTOK)
196 adios (*form, "unable to open form file");
198 if ((in = open (etcpath (def), O_RDONLY)) == NOTOK)
199 adios (def, "unable to open default components file");