home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The Datafile PD-CD 4
/
DATAFILE_PDCD4.iso
/
unix
/
unixlib36d
/
src
/
stdio
/
c
/
fopen
< prev
next >
Wrap
Text File
|
1994-03-08
|
3KB
|
150 lines
static char sccs_id[] = "@(#) fopen.c 3.0 " __DATE__ " HJR";
/* fopen.c (c) Copyright 1990 H.Rogers */
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include "fcntl.h"
extern int isatty (int);
extern int open (char *, int, int);
extern long lseek (int, long, int);
#define OPERM 0666 /* open() permission */
#ifndef O_OMASK
#define O_OMASK (O_RDONLY|O_WRONLY|O_RDWR)
#endif
__STDIOLIB__
static FILE *__fopen (const char *, const char *, FILE *);
static FILE *__fdopen (int, int, FILE *);
FILE *
fopen (register const char *file, register const char *mode)
{
register FILE *f;
register int i;
for (i = 0, f = __iob; i < FOPEN_MAX; i++, f++)
if (!fisopen (f))
return (__fopen (file, mode, f));
return (0);
}
FILE *
freopen (register const char *file, register const char *mode,
register FILE * f)
{
if (fisopen (f))
if (fclose (f))
return (0);
return (__fopen (file, mode, f));
}
FILE *
fdopen (register int fd, register const char *mode)
{
register FILE *f;
register int flag, i;
for (i = 0, f = __iob; i < FOPEN_MAX; i++, f++)
if (!fisopen (f))
goto open;
return (0);
open:i = *mode;
if (i == 'r')
flag = _IOREAD;
else if (i == 'w')
flag = _IOWRITE;
else if (i == 'a')
flag = _IOWRITE | _IOAPPEND;
else
return (0);
if (i = *++mode)
while (i)
{
if (i == '+')
flag |= _IOREAD | _IOWRITE;
i = *++mode;
}
return (__fdopen (fd, flag, f));
}
static FILE *
__fopen (register const char *file, register const char *mode,
register FILE * f)
{
register int flag, oflag, i;
i = *mode;
if (i == 'r')
{
flag = _IOREAD;
oflag = O_RDONLY;
}
else if (i == 'w')
{
flag = _IOWRITE;
oflag = O_WRONLY | O_CREAT | O_TRUNC;
}
else if (i == 'a')
{
flag = _IOWRITE | _IOAPPEND;
oflag = O_WRONLY | O_CREAT;
}
else
return (0);
if (i = *++mode)
while (i)
{
if (i == 'b')
oflag |= O_BINARY;
else if (i == '+')
{
flag |= _IOREAD | _IOWRITE;
oflag = (oflag & (~(O_OMASK | O_TRUNC))) | O_RDWR;
}
i = *++mode;
}
if ((i = open ((char *) file, oflag, OPERM)) < 0)
return (0);
return (__fdopen (i, flag, f));
}
static FILE *
__fdopen (register int fd, register int flag, register FILE * f)
{
f->i_ptr = f->i_base = 0;
f->o_ptr = f->o_base = 0;
f->i_cnt = f->o_cnt = 0;
if (isatty (f->fd = fd))
{
f->pos = 0;
flag |= _IOTTY;
f->flag = (flag & _IOBF) ? flag : (flag | _IOLBF);
}
else
{
if (flag & _IOAPPEND)
f->pos = (fpos_t) lseek (fd, 0L, 2);
else
f->pos = (fpos_t) lseek (fd, 0L, 0);
f->flag = (flag & _IOBF) ? flag : (flag | _IOFBF);
}
f->bufsiz = BUFSIZ;
return (f);
}