/* -*- C -*- * FILE: "/home/y1zln/pub/zimg/path.c" * LAST MODIFICATION: "Fr, 29 Okt 2004 15:30:21 CEST (y1zln)" * (C) 2003 - 2004 by Johannes Zellner, * $Id: path.c,v 1.3 2004/10/30 12:22:49 joze Exp $ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "path.h" #include #include #include #include #include #if defined HAVE_SYS_STAT_H && defined HAVE_SYS_STAT_H # include # include #endif static char* path_cat(const char* filename, const char* subdir, const char* path_prefix) { char* path = (char*)malloc(strlen(path_prefix) + (subdir ? strlen(subdir) : 0) + strlen(filename) + 4); if (!path) { perror("path_cat->path"); exit(2); } strcpy(path, path_prefix); strcat(path, "/"); if (subdir) { strcat(path, subdir); strcat(path, "/"); } strcat(path, filename); return path; } /* returns 0 on success */ static int access_file(char* path) { int status; if ((status = access(path, R_OK))) return status; #if defined HAVE_SYS_STAT_H && defined HAVE_SYS_STAT_H { struct stat buf; stat(path, &buf); if (S_ISDIR(buf.st_mode)) return 1; /* directory */ } #endif return 0; /* success, not a directory */ } char* search_file(const char* filename, const char* subdir, const char* path_prefix, unsigned char absolute) { char* path = (char*)0; static char* path_home_zimg = (char*)0; static char* path_cwd = (char*)0; if (filename && '/' == filename[0]) { return strdup(filename); } if (!path_home_zimg) { char* home = getenv("HOME"); if (home) { path_home_zimg = malloc(sizeof (char) * (strlen(home) + 8)); strcpy(path_home_zimg, home); strcat(path_home_zimg, "/.zimg"); } } if (absolute) { if (!path_cwd) { int i; for (i = 1; i < 10; i++) { path_cwd = (char*)malloc(sizeof (char) * 0x100 * i); if (!path_cwd) { perror("search_file->path_cwd"); exit(2); } if (getcwd(path_cwd, 0x100 * i)) break; else { free(path_cwd); path_cwd = (char*)0; } } } path = path_cat(filename, (char*)0, path_cwd); } else { path = strdup(filename); } if (access_file(path)) { if (path_home_zimg) { if (path) free(path); /* e.g. ~/.zimg/expr/ */ path = path_cat(filename, subdir, path_home_zimg); } if (access_file(path)) { if (path) free(path); /* e.g. /usr/local/lib/zimg-4.7.7/expr/ */ path = path_cat(filename, subdir, path_prefix); if (access_file(path)) { if (path) free(path); path = (char*)0; } } } return path; }