home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / PFOPEN.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  2KB  |  76 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. /*
  4.  *  Written and released to the public domain by David Engel.
  5.  *
  6.  *  This function attempts to open a file which may be in any of
  7.  *  several directories.  It is particularly useful for opening
  8.  *  configuration files.  For example, PROG.EXE can easily open
  9.  *  PROG.CFG (which is kept in the same directory) by executing:
  10.  *
  11.  *      cfg_file = pfopen("PROG.CFG", "r", getenv("PATH"));
  12.  *
  13.  *  NULL is returned if the file can't be opened.
  14.  */
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <string.h>
  19. #include "snpdosys.h"
  20.  
  21. FILE *pfopen(const char *name, const char *mode, const char *dirs)
  22. {
  23.     char *ptr;
  24.     char *tdirs;
  25.     FILE *file = NULL;
  26.  
  27.     if (dirs == NULL || dirs[0] == '\0')
  28.         return NULL;
  29.  
  30.     if ((tdirs = malloc(strlen(dirs)+1)) == NULL)
  31.         return NULL;
  32.  
  33.     strcpy(tdirs, dirs);
  34.  
  35.     for (ptr = strtok(tdirs, SEP_CHARS); file == NULL && ptr != NULL;
  36.         ptr = strtok(NULL, SEP_CHARS))
  37.     {
  38.         size_t len;
  39.         char work[FILENAME_MAX];
  40.  
  41.         strcpy(work, ptr);
  42.         len = strlen(work);
  43.         if (len && work[len-1] != '/' && work[len-1] != '\\')
  44.             strcat(work, "/");
  45.         strcat(work, name);
  46.  
  47.         file = fopen(work, mode);
  48.     }
  49.  
  50.     free(tdirs);
  51.  
  52.     return file;
  53. }
  54.  
  55. #ifdef TEST
  56.  
  57. int main(int argc, char **argv)
  58. {
  59.     FILE *file;
  60.  
  61.     if (argc != 4)
  62.     {
  63.         fprintf(stderr, "usage: pfopen name mode dirs\n");
  64.         exit(1);
  65.     }
  66.  
  67.     file = pfopen(argv[1], argv[2], argv[3]);
  68.  
  69.     printf("%s \"%s\" with mode \"%s\"\n", (file == NULL) ?
  70.         "Could not open" : "Opened", argv[1], argv[2]);
  71.  
  72.     return 0;
  73. }
  74.  
  75. #endif /* TEST */
  76.