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 / freopen.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-12-12  |  1.8 KB  |  90 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <unistd.h>
  6. #ifdef __GNUC__
  7. #include <dos/dos.h>
  8. #include <inline/dos.h>
  9. #endif
  10. #ifndef __GNUC__
  11. #include <clib/dos_protos.h>
  12. #endif
  13.  
  14. extern void __seterrno(void);
  15. extern int __fflush(FILE *stream);
  16.  
  17. FILE *freopen(const char *filename,const char *mode,FILE *stream)
  18. { int error;
  19.   error=__fflush(stream);
  20.   if(stream->file>2)
  21.   { close(stream->file);
  22.     if(stream->name!=NULL) /* file is temporary */
  23.     { BPTR cd;
  24.       cd=CurrentDir(stream->tmpdir); /* cd t: */
  25.       if(!DeleteFile(stream->name))  /* delete file */
  26.       { __seterrno();
  27.         error=1; }
  28.       free(stream->name); /* free filename */
  29.       stream->name=NULL;
  30.       UnLock(CurrentDir(cd)); /* cd back, unlock t: */
  31.     }
  32.     stream->file=0l;
  33.   }
  34.   if(error)
  35.     return NULL;
  36.  
  37.   if(filename!=NULL)
  38.   { long file;
  39.     long flags=O_RDONLY;
  40.     int append=0,plus=1;
  41.     if(mode!=NULL)
  42.     { switch(mode[0])
  43.       {
  44.         case 'r':
  45.           break;
  46.         case 'w':
  47.           flags=O_WRONLY|O_CREAT|O_TRUNC;
  48.           break;
  49.         case 'a':
  50.           flags=O_WRONLY|O_CREAT;
  51.           append=1;
  52.           break;
  53.         default:
  54.           return NULL;
  55.       }
  56.       if(mode[1]=='b')
  57.         plus=2;
  58.       switch(mode[plus])
  59.       {
  60.         case '+':
  61.           flags=(flags&~O_ACCMODE)|O_RDWR;
  62.           if(mode[plus+1])
  63.             return NULL;
  64.           break;
  65.         case '\0':
  66.           break;
  67.         default:
  68.           return NULL;
  69.       }
  70.     }
  71.  
  72.     if((long)filename<4)
  73.       file=(long)filename-1;
  74.     else
  75.       if((file=open(filename,flags,0777))<0)
  76.         return NULL;
  77.     
  78.     if(append&&lseek(file,0,SEEK_END)<0)
  79.       return NULL;
  80.  
  81.     stream->flags&=~0x6f; /* clear a lot of flags */
  82.     if(isatty(file))
  83.       stream->flags|=1; /* set linebuffered flag */
  84.    
  85.     stream->file=file;
  86.   }
  87.  
  88.   return stream;
  89. }
  90.