home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / libnix-0.8-src.lha / libnix-0.8 / sources / nix / stdio / fopen.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-12-12  |  1.9 KB  |  85 lines

  1. #include <stdio.h>
  2. #include <stdlib.h> /* If you use normal file I/O,
  3.                        the memory functions don't count that much on memory */
  4. #include <debuglib.h>
  5. #include <errno.h>
  6. #ifdef __GNUC__
  7. #include <inline/exec.h>
  8. #endif
  9. #ifndef __GNUC__
  10. #include <clib/exec_protos.h>
  11. #endif
  12. #include <exec/lists.h>
  13. #include <exec/nodes.h>
  14. #include <stabs.h>
  15.  
  16. struct filenode
  17. {
  18.   struct MinNode node;
  19.   FILE FILE;
  20. };
  21.  
  22. struct MinList __filelist= /* list of open files (fflush() needs also access) */
  23. {
  24.   (struct MinNode *)&__filelist.mlh_Tail,
  25.   NULL,
  26.   (struct MinNode *)&__filelist.mlh_Head
  27. };
  28.  
  29. extern void __chkabort(void);
  30.  
  31. FILE *fopen(const char *filename,const char *mode)
  32. {
  33.   struct filenode *node;
  34.   __chkabort();
  35.   if((node=(struct filenode *)calloc(1,sizeof(struct filenode)))!=NULL)
  36.   {
  37.     if((node->FILE.buffer=(char *)malloc(BUFSIZ))!=NULL)
  38.     {
  39.       node->FILE.bufsize=BUFSIZ;
  40.       node->FILE.flags|=0x80; /* Buffer is malloc'ed */
  41.       if(freopen(filename,mode,&node->FILE)!=NULL)
  42.       { AddHead((struct List *)&__filelist,(struct Node *)&node->node);
  43.         return &node->FILE; }
  44.       free(node->FILE.buffer);
  45.     }
  46.     else
  47.       errno=ENOMEM;
  48.     free(node);
  49.   }
  50.   else
  51.     errno=ENOMEM;
  52.   return NULL;
  53. }
  54.  
  55. int fclose(FILE *stream)
  56.   int retval=0;
  57.   struct filenode *node; /* no __chkabort(), 'cause __exitio is called at abort() */
  58.   if(stream==NULL)
  59.   {
  60. #ifdef DEBUG_LIB
  61.     FATALERROR("NULL pointer fclose'd\n");
  62. #endif
  63.     return EOF;
  64.   }
  65.   retval=freopen(NULL,NULL,stream)==NULL?EOF:0;
  66.   if(stream->flags&0x80) /* Free buffer if necessary */
  67.   { free(stream->buffer);
  68.     stream->buffer=NULL; }
  69.   node=(struct filenode *)((struct MinNode *)stream-1);
  70.   Remove((struct Node *)&node->node);
  71.   free(node);
  72.   return retval;
  73. }
  74.  
  75. void __exitstdfio(void)
  76. {
  77.   struct MinNode *node;
  78.   while((node=__filelist.mlh_Head)->mln_Succ!=NULL)
  79.     fclose(&((struct filenode *)node)->FILE);
  80. }
  81.  
  82. /* Call our private destructor at cleanup */
  83. ADD2EXIT(__exitstdfio,-20);
  84.