summaryrefslogtreecommitdiff
path: root/zwgc/file.c
diff options
context:
space:
mode:
authorGravatar Marc Horowitz <marc@mit.edu>1989-11-01 20:02:01 +0000
committerGravatar Marc Horowitz <marc@mit.edu>1989-11-01 20:02:01 +0000
commitd13d8a046838ce3d0e2643bb5b49f2ff77d679ca (patch)
tree05737bc11e3461836ce817939b9129ed58545ac7 /zwgc/file.c
parentfd994e4099ad66fb3bf26cd636ca5d5cae72da68 (diff)
Initial revision
Diffstat (limited to 'zwgc/file.c')
-rw-r--r--zwgc/file.c99
1 files changed, 99 insertions, 0 deletions
diff --git a/zwgc/file.c b/zwgc/file.c
new file mode 100644
index 0000000..a46a4f5
--- /dev/null
+++ b/zwgc/file.c
@@ -0,0 +1,99 @@
+#include <errno.h>
+#include <sys/types.h>
+#include <stdio.h>
+#include <pwd.h>
+#include "new_memory.h"
+#include "new_string.h"
+#include "error.h"
+
+/*
+ * char *get_home_directory()
+ *
+ * Effects: Attempts to locate the user's (by user, the owner of this
+ * process is meant) home directory & return its pathname.
+ * Returns NULL if unable to do so. Does so by first checking
+ * the environment variable HOME. If it is unset, falls back
+ * on the user's password entry.
+ * Note: The returned pointer may point to a static buffer & hence
+ * go away on further calls to getenv, get_home_directory,
+ * getpwuid, or related calls. The caller should copy it
+ * if necessary.
+ */
+
+char *get_home_directory()
+{
+ char *result;
+ char *getenv();
+ struct passwd *passwd_entry;
+
+ if (result = getenv("HOME"))
+ return(result);
+
+ if (!(passwd_entry = getpwuid(getuid())))
+ return(NULL);
+
+ return(passwd_entry->pw_dir);
+}
+
+/*
+ *
+ */
+
+FILE *locate_file(override_filename, home_dir_filename, fallback_filename)
+ char *override_filename;
+ char *home_dir_filename;
+ char *fallback_filename;
+{
+ char *filename;
+ FILE *result;
+
+ errno = 0;
+
+ if (override_filename) {
+ if (string_Eq(override_filename, "-"))
+ return(stdin);
+
+ result = fopen(override_filename, "r");
+ if (!(result = fopen(override_filename, "r"))) {
+ /* <<<>>> */
+ fprintf(stderr, "zwgc: error while opening %s for reading: ",
+ override_filename);
+ perror("");
+ }
+ return(result);
+ }
+
+ if (home_dir_filename) {
+ if (filename = get_home_directory()) {
+ filename = string_Concat(filename, "/");
+ filename = string_Concat2(filename, home_dir_filename);
+ result = fopen(filename, "r");
+ if (result) {
+ free(filename);
+ return(result);
+ }
+ if (errno != ENOENT) {
+ /* <<<>>> */
+ fprintf(stderr, "zwgc: error while opening %s for reading: ",
+ filename);
+ perror("");
+ free(filename);
+ return(result);
+ }
+ free(filename);
+ } else
+ ERROR("unable to find your home directory.\n");
+ }
+
+ if (fallback_filename) {
+ if (!(result = fopen(fallback_filename, "r"))) {
+ /* <<<>>> */
+ fprintf(stderr, "zwgc: error while opening %s for reading: ",
+ fallback_filename);
+ perror("");
+ }
+ return(result);
+ }
+
+ return(NULL);
+}