home *** CD-ROM | disk | FTP | other *** search
/ PC Extra Super CD 1998 January / PCPLUS131.iso / DJGPP / V2 / DJLSR201.ZIP / src / libc / posix / fcntl / open.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-07-23  |  1.6 KB  |  63 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  3. #include <libc/stubs.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <unistd.h>
  10. #include <sys/stat.h>
  11. #include <io.h>
  12.  
  13. #include <libc/dosio.h>
  14.  
  15. int
  16. open(const char* filename, int oflag, ...)
  17. {
  18.   int fd, dmode, bintext;
  19.  
  20.   /* Check this up front, to reduce cost and minimize effect */
  21.   if ((oflag & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
  22.     if (__file_exists(filename))
  23.     {
  24.       /* file exists and we didn't want it to */
  25.       errno = EEXIST;
  26.       return -1;
  27.     }
  28.  
  29.   /* figure out what mode we're opening the file in */
  30.   bintext = oflag & (O_TEXT | O_BINARY);
  31.   if (!bintext)
  32.     bintext = _fmode & (O_TEXT | O_BINARY);
  33.   if (!bintext)
  34.     bintext = O_BINARY;
  35.  
  36.   /* DOS doesn't want to see these bits */
  37.   oflag &= ~(O_TEXT | O_BINARY);
  38.  
  39.   dmode = (*((&oflag)+1) & S_IWUSR) ? 0 : 1;
  40.  
  41.   fd = _open(filename, oflag);
  42.   if (fd == -1 && oflag & O_CREAT)
  43.     fd = _creat(filename, dmode);
  44.  
  45.   if (fd == -1)
  46.     return fd;    /* errno already set by _open or _creat */
  47.  
  48.   if (oflag & O_TRUNC)
  49.     if (_write(fd, 0, 0) < 0)
  50.       return -1;
  51.  
  52.   /* we do this last because _open and _create set it also. */
  53.   /* force setmode() to do ioctl() for cooked/raw */
  54.   __file_handle_set(fd, bintext ^ (O_BINARY|O_TEXT));
  55.   /* this will do cooked/raw ioctl() on character devices */
  56.   setmode(fd, bintext);
  57.  
  58.   if(oflag & O_APPEND)
  59.     lseek(fd, 0, SEEK_END);
  60.  
  61.   return fd;
  62. }
  63.