home *** CD-ROM | disk | FTP | other *** search
- // Zinc Interface Library - PATH.CPP
- // COPYRIGHT (C) 1990, 1991. All Rights Reserved.
- // Zinc Software Incorporated. Pleasant Grove, Utah USA
-
- #include "ui_gen.hpp"
- #include <string.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <io.h>
- #include <fcntl.h>
- #include <dir.h>
-
- UI_PATH::UI_PATH()
- {
- envPath = getenv("PATH");
- prgPath = 0;
- cwdPath = 0;
- fileName = 0;
- pathName = 0;
- pathPtr = 0;
- }
-
- UI_PATH::UI_PATH(char *programPath, int rememberCwd)
- {
- envPath = getenv("PATH");
- prgPath = 0;
- if (_osmajor >= 3 && programPath)
- {
- char *tail = strrchr(programPath, '\\');
- if (tail)
- {
- if (*(tail - 1) == ':')
- tail++; // Leave in the slash if root dir.
- int prgLen = (int) (tail - programPath);
- prgPath = new char[prgLen + 1];
- memcpy(prgPath, programPath, prgLen);
- *(prgPath + prgLen) = '\0';
- }
- }
- cwdPath = 0;
- if (rememberCwd)
- {
- char cwd[128];
- getcwd(cwd, sizeof(cwd));
- if ( !prgPath || strcmp(prgPath, cwd) != 0 )
- cwdPath = ui_strdup(cwd);
- }
- fileName = 0;
- pathName = 0;
- pathPtr = 0;
- }
-
- UI_PATH::~UI_PATH()
- {
- delete prgPath;
- delete cwdPath;
- delete fileName;
- delete pathName;
- }
-
- void UI_PATH::SetFileName(const char *a_fileName)
- {
- delete fileName;
- if (a_fileName)
- fileName = ui_strdup(a_fileName);
- else
- fileName = 0;
- pathPtr = envPath;
- pathCnt = (prgPath || cwdPath) ? 1 : 3;
- }
-
- char *UI_PATH::NextPathName()
- {
- delete pathName;
- pathName = 0;
- int len;
- int addSlash;
- int fileNameLen = fileName ? strlen(fileName) : 0;
- while (pathCnt == 1 || pathCnt == 2)
- {
- char *ptr = (pathCnt == 1) ? prgPath : cwdPath;
- pathCnt++;
- if (ptr)
- {
- len = strlen(ptr);
- addSlash = *(ptr + len - 1) == '\\' ? 0 : 1;
- pathName = new char[len + addSlash + fileNameLen + 1];
- strcpy(pathName, ptr);
- if (fileName)
- {
- if (addSlash)
- strcat(pathName, "\\");
- strcat(pathName, fileName);
- }
- return pathName;
- }
- }
- if (!pathPtr)
- return 0;
- char *s = strchr(pathPtr, ';');
- if (!s)
- len = strlen(pathPtr);
- else
- len = (int) (s - pathPtr);
- addSlash = 0;
- if (fileName && pathPtr[len - 1] != '\\')
- addSlash = 1;
- pathName = new char[len + addSlash + fileNameLen + 1];
- memcpy(pathName, pathPtr, len);
- if (addSlash)
- pathName[len++] = '\\';
- if (fileName)
- strcpy(pathName + len, fileName);
- else
- pathName[len] = '\0';
- pathPtr = s ? s + 1 : 0;
- return pathName;
- }
-
- int UI_PATH::OpenFile(const char *file, unsigned int mode)
- {
- int handle;
-
- if (_osmajor >= 3 && mode == O_RDONLY)
- mode = O_DENYWRITE;
- /* try specification as is */
- if ((handle = open(file, mode)) >= 0)
- return (handle);
-
- if (file[0] == '\\' || strchr(file, ':'))
- return (-1); // Absolute file spec. or drive specifier.
-
- SetFileName(file);
- char *pathName;
- while ((pathName = NextPathName()) != 0)
- if ((handle = open(pathName, mode)) >= 0)
- return (handle);
- return (-1);
- }
-