+FILE *ask_and_open(const char *filename, const char *what, const char *mode) {
+ FILE *r;
+ char *directory;
+ char buf[PATH_MAX];
+ char buf2[PATH_MAX];
+ size_t len;
+
+ /* Check stdin and stdout */
+ if(isatty(0) && isatty(1)) {
+ /* Ask for a file and/or directory name. */
+ fprintf(stdout, _("Please enter a file to save %s to [%s]: "),
+ what, filename);
+ fflush(stdout);
+
+ if(fgets(buf, sizeof buf, stdin) < 0) {
+ fprintf(stderr, _("Error while reading stdin: %s\n"),
+ strerror(errno));
+ return NULL;
+ }
+
+ len = strlen(buf);
+ if(len)
+ buf[--len] = 0;
+
+ if(len)
+ filename = buf;
+ }
+
+#ifdef HAVE_MINGW
+ if(filename[0] != '\\' && filename[0] != '/' && !strchr(filename, ':')) {
+#else
+ if(filename[0] != '/') {
+#endif
+ /* The directory is a relative path or a filename. */
+ directory = get_current_dir_name();
+ snprintf(buf2, sizeof buf2, "%s/%s", directory, filename);
+ filename = buf2;
+ }
+
+ umask(0077); /* Disallow everything for group and other */
+
+ /* Open it first to keep the inode busy */
+
+ r = fopen(filename, mode);
+
+ if(!r) {
+ fprintf(stderr, _("Error opening file `%s': %s\n"), filename, strerror(errno));
+ return NULL;
+ }
+
+ return r;
+}
+