home *** CD-ROM | disk | FTP | other *** search
/ Atari FTP / ATARI_FTP_0693.zip / ATARI_FTP_0693 / Mint / mntlib25.zoo / tmpfile.c < prev    next >
C/C++ Source or Header  |  1992-09-05  |  2KB  |  84 lines

  1. /* tmpfile.c: create a temporary file that will be deleted when exit()
  2.    is called.
  3.    Written by Eric R. Smith and placed in the public domain.
  4. */
  5.  
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8.  
  9. extern int __mint;
  10.  
  11. static void delete_tmpfiles __PROTO((void));
  12.  
  13. typedef struct {
  14.     char    *name;
  15.     FILE    *fp;
  16. } FILE_RECORD;
  17.  
  18. static FILE_RECORD    *file_to_delete;
  19. static int        numtmps = -1;
  20.  
  21. static void
  22. delete_tmpfiles()
  23. {
  24.     int i;
  25.  
  26.     for (i = 0; i <= numtmps; i++)
  27.     {
  28.         fclose(file_to_delete[i].fp);
  29.         remove(file_to_delete[i].name);
  30.     }
  31. }
  32.  
  33. FILE *tmpfile()
  34. {
  35.     char *junknam;
  36.     FILE *junkfil;
  37.  
  38.     if ( ((junknam = tmpnam(NULL)) == NULL) || 
  39.         ((junkfil = fopen(junknam, "w+b")) == NULL ))
  40.     {
  41.         if(junknam)
  42.             free(junknam);
  43.         return NULL;
  44.     }
  45.  
  46. /* in MiNT 0.9 and above, we can often unlink a file and continue to use
  47.  * it; some file systems may return EACCDN for unlinking an open file,
  48.  * in which case we use the old method of unlinking the file at exit
  49.  */
  50.     if (__mint >= 9) {
  51.         if (remove(junknam) == 0)
  52.             return junkfil;
  53.     }
  54.  
  55.     if((++numtmps) == 0)
  56.         file_to_delete = (FILE_RECORD *)malloc((size_t)sizeof(FILE_RECORD));
  57.     else
  58.         file_to_delete = (FILE_RECORD *)realloc(file_to_delete,
  59.                     (size_t)((numtmps+1) * sizeof(FILE_RECORD)));
  60.     if(file_to_delete == (FILE_RECORD *)NULL)
  61.     {
  62.         fclose(junkfil);
  63.         remove(junknam);
  64.         free(junknam);
  65.         numtmps -= 1;
  66.         return NULL;    /* outa mem */
  67.     }
  68. /* install this in the list of temporary files to be deleted at exit */
  69.     file_to_delete[numtmps].name = junknam;
  70.     file_to_delete[numtmps].fp   = junkfil;
  71.  
  72. /* if this is the first, install the delete routine */
  73.     if (numtmps == 0)
  74.         if(atexit(delete_tmpfiles) != 0)
  75.         {    /* atexit failed -- cleanup */
  76.             delete_tmpfiles();
  77.             numtmps = -1;
  78.             free(file_to_delete[0].name);
  79.             free(file_to_delete);
  80.             return NULL;
  81.         }
  82.     return junkfil;
  83. }
  84.