home *** CD-ROM | disk | FTP | other *** search
- /* C.Mktemp: Make a temporary file name */
-
- #include "kernel.h"
- #include <string.h>
- #include <stdlib.h>
-
- #include "utils.h"
-
- #define ReadCat 5
-
- /* Create a temporary file name by adding a directory prefix to file.
- * If the external variable temp_dir is not zero, this directory will be
- * used. Otherwise, the following are used, in order.
- * 1. <Tmp$Dir>
- * 2. &.Tmp
- * 3. The current directory.
- * The function returns zero on an error (temp_dir is not a directory, or
- * malloc() failed), otherwise it returns a malloc-ed string containing
- * the required name.
- */
-
- static char *concat (const char *dir, const char *file);
-
- static char *dirs[] =
- {
- "<Tmp$Dir>",
- "&.Tmp",
- "",
- 0
- };
-
- char *temp_dir = 0;
-
- char *mktemp (const char *file)
- {
- char **d;
- _kernel_osfile_block blk;
-
- /* First, try the supplied directory */
- if ( temp_dir )
- {
- if ( _kernel_osfile(ReadCat,temp_dir,&blk) != 2 )
- {
- /* Is it a filing system name only? */
- int len = strlen(temp_dir);
- int res;
- char *name;
-
- if (temp_dir[len-1] != ':')
- return 0;
-
- /* One extra, just in case file == "", for the '@' */
- name = malloc(len + strlen(file) + 2);
-
- if (name == 0)
- return 0;
-
- strcpy(name,temp_dir);
- name[len] = '@';
- name[len+1] = '\0';
-
- res = _kernel_osfile(ReadCat,name,&blk);
-
- if (res != 2)
- {
- free(name);
- return 0;
- }
-
- strcpy(&name[len],file);
- return name;
- }
-
- return concat(temp_dir,file);
- }
-
- /* Otherwise, go through the list... */
- for ( d = dirs; *d; ++d )
- {
- /* Is this the current directory? */
- if ( *d[0] == '\0' )
- {
- char *res = malloc(strlen(file)+1);
- if ( res )
- strcpy(res,file);
- return res;
- }
-
- /* Is this a valid directory? */
- if ( _kernel_osfile(ReadCat,*d,&blk) == 2 )
- return concat(*d,file);
- }
-
- /* Couldn't find anything... */
- return 0;
- }
-
- static char *concat (const char *dir, const char *file)
- {
- char *result = malloc(strlen(dir)+strlen(file)+2);
- char *p = result;
-
- if ( result == 0 )
- return 0;
-
- while ( *dir )
- *p++ = *dir++;
-
- *p++ = '.';
- while ( *file )
- *p++ = *file++;
-
- *p = '\0';
-
- return result;
- }
-
- /* ----------------------------------------------------------------- */
-
- #ifdef test
-
- #include <stdio.h>
-
- int main (int argc, char *argv[])
- {
- char *tmp;
-
- if ( argc != 2 && argc != 3 )
- {
- fprintf(stderr,"Usage: %s file [dir]\n",argv[0]);
- return 1;
- }
-
- if ( argc == 3 )
- temp_dir = argv[2];
-
- tmp = mktemp (argv[1]);
-
- printf("Temp file = %s\n", tmp ? tmp : "<Not possible>");
-
- return 0;
- }
-
- #endif
-