+ fflush(fp);
+ if (ferror(fp))
+ warn("fwrite %s", filename);
+ fclose(fp);
+}
+
+/*
+ * Given a save file name (possibly from fgetln, so without terminating NUL),
+ * determine the name of the file to be saved to by adding the HOME
+ * directory if the name does not contain a slash. Name will be allocated
+ * with malloc(3).
+ */
+char *
+save_file_name(filename, len)
+ const char *filename;
+ size_t len;
+{
+ char *home;
+ char *newname;
+ size_t tmpl;
+
+ if (memchr(filename, '/', len)) {
+ newname = malloc(len + 1);
+ if (newname == NULL) {
+ warn(NULL);
+ return NULL;
+ }
+ memcpy(newname, filename, len);
+ newname[len] = 0;
+ } else {
+ home = getenv("HOME");
+ if (home != NULL) {
+ tmpl = strlen(home);
+ newname = malloc(tmpl + len + 2);
+ if (newname == NULL) {
+ warn(NULL);
+ return NULL;
+ }
+ memcpy(newname, home, tmpl);
+ newname[tmpl] = '/';
+ memcpy(newname + tmpl + 1, filename, len);
+ newname[tmpl + len + 1] = 0;
+ } else {
+ newname = malloc(len + 1);
+ if (newname == NULL) {
+ warn(NULL);
+ return NULL;
+ }
+ memcpy(newname, filename, len);
+ newname[len] = 0;
+ }
+ }
+ return newname;