freopen(), access()

YANG Liqun yang at nff.ncl.omron.co.jp
Wed Jan 23 16:55:07 AEST 1991


In arcticle <15715hh2x at vax5.cit.cornell.edu> writes:

>Could someone please explain the functions freopen() and access()? I have some
>source that calls these functions but they aren't included with my compiler.
>If someone could tell me what they do I may be able to write them myself.
>Replies through Email would be greatly appreciate.

access() is a system call of Unix OS, it investigate the access permision of
given file:

     #include <sys/file.h>

     #define R_OK    4/* test for read permission */
     #define W_OK    2/* test for write permission */
     #define X_OK    1/* test for execute (search) permission */
     #define F_OK    0/* test for presence of file */

     accessible = access(path, mode)
     int accessible;
     char *path;
     int mode;

As far I know, it is written in assembler in System V. First it looks for the
inode number of given file(use ls -i, you can do it), and then read the 
inode information from disk and then find what access permission the file has.

For freopen(), you can easily rewrite it in C.

     FILE *freopen(filename, type, stream)
     char *filename, *type;
     FILE *stream;

First it closes "stream" by calling fclose. Then calls "open" system call with
flag information supplied in "type" to open a file with name "filename"(it may
be a different file). The file descriptor returned by "open" system call and
flag information in "type" will be used to replace fields in FILE struct:

    ...
    oflag = O_RDWR /* O_RDONLY, O_WRONLY, and etc., according to type */
    if ((fd = open(filename, oflag, 0666)) <0)
		return (NULL);
    stream->_cnt = 0; /* File read & write offset */
    stream-> _file = fd;
    stream->_flag = _IORW; /* or _IOREAD, _IOWRT, according to type*/
   ...
   /* If file is opened as "a" type, you need to use lseek to move file pointer
      to the end of the file */
   Finally, set
    _bufend(stream) = stream->_base = stream->ptr = NULL;
   return(stream);

So freopen() open another file but use the old FILE struct by closing the old
file and replacing contents of FILE struct.

--
;  Li-qun Yang			OMRON Computer Technology R&D lab
;  yang at nff.ncl.omron.co.jp	tel: 075-951-5111  fax: 075-956-7403



More information about the Comp.lang.c mailing list