00001
00002
00003
00004
00005
00006
00007
00008
00009 #if HAVE_SYS_FILE_H
00010 # include <sys/file.h>
00011 #endif
00012
00013 #if HAVE_SYS_STAT_H
00014 # include <sys/stat.h>
00015 #endif
00016
00017 #include "util.h"
00018
00025 int
00026 util_check_file(char const *filename, char const *mode)
00027 {
00028 #if defined(HAVE_SYS_STAT_H)
00029 struct stat stat_rec;
00030 int access_char = mode[0];
00031 int access_mode = R_OK;
00032
00033
00034
00035 if (stat(filename,&stat_rec) == 0 && S_ISREG(stat_rec.st_mode)) {
00036 if (access_char == 'w') {
00037 access_mode = W_OK;
00038 } else if (access_char == 'x') {
00039 access_mode = X_OK;
00040 }
00041 return access(filename,access_mode) == 0;
00042 }
00043 return 0;
00044
00045 #else
00046
00047 FILE *fp;
00048 int got_file;
00049
00050 if (strcmp(mode, "x") == 0) {
00051 mode = "r";
00052 }
00053 fp = fopen(filename, mode);
00054 got_file = (fp != 0);
00055 if (fp != 0) {
00056 (void) fclose(fp);
00057 }
00058 return got_file;
00059
00060 #endif
00061 }
00062
00070 char *
00071 util_path_search(char const *prog)
00072 {
00073 #ifdef HAVE_GETENV
00074 return util_file_search(prog, getenv("PATH"), "x");
00075 #else
00076 return util_file_search(prog, NIL(char), "x");
00077 #endif
00078 }
00079
00080 char *
00081 util_file_search(
00082 char const *file ,
00083 char *path ,
00084 char const *mode )
00085 {
00086 int quit;
00087 char *buffer, *filename, *save_path, *cp;
00088
00089 if (path == 0 || strcmp(path, "") == 0) {
00090 path = ".";
00091 }
00092
00093 save_path = path = util_strsav(path);
00094 quit = 0;
00095 do {
00096 cp = strchr(path, ':');
00097 if (cp != 0) {
00098 *cp = '\0';
00099 } else {
00100 quit = 1;
00101 }
00102
00103
00104 if (strcmp(path, ".") == 0) {
00105 buffer = util_strsav(file);
00106 } else {
00107 buffer = ALLOC(char, strlen(path) + strlen(file) + 4);
00108 (void) sprintf(buffer, "%s/%s", path, file);
00109 }
00110 filename = util_tilde_expand(buffer);
00111 FREE(buffer);
00112
00113
00114 if (util_check_file(filename, mode)) {
00115 FREE(save_path);
00116 return filename;
00117 }
00118 FREE(filename);
00119 path = ++cp;
00120 } while (! quit);
00121
00122 FREE(save_path);
00123 return 0;
00124 }