home *** CD-ROM | disk | FTP | other *** search
/ Unix System Administration Handbook 1997 October / usah_oct97.iso / news / cnews.tar / libcnews / fopenexcl.c < prev    next >
C/C++ Source or Header  |  1995-04-27  |  724b  |  34 lines

  1. /*
  2.  * fopenexcl(name) - fopen(name, "w+") with error if name exists
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <fcntl.h>
  8. #ifndef O_RDONLY        /* using our fake fcntl.h; maybe it's 4.2? */
  9. #include <sys/file.h>
  10. #endif
  11.  
  12. #ifdef O_RDONLY            /* good, we have a 3-arg open() */
  13. #define    OPENRW(f)    open(f, O_RDWR|O_CREAT|O_EXCL, 0666)
  14. #else                /* don't -- must fake it */
  15. #include <sys/stat.h>
  16. static struct stat testbuf;
  17. #define    OPENRW(f)    ((stat(f, &testbuf) < 0) ? \
  18.                 ((void)close(creat(f, 0666)), open(f, 2)) : \
  19.                 -1)
  20. #endif
  21.  
  22. FILE *
  23. fopenexcl(name)
  24. register char *name;
  25. {
  26.     register int fd;
  27.  
  28.     fd = OPENRW(name);
  29.     if (fd < 0)
  30.         return NULL;        /* name existed or couldn't be made */
  31.     else
  32.         return fdopen(fd, "w+");
  33. }
  34.