File pointer to a memory location?

Chris Torek chris at mimsy.umd.edu
Thu Sep 13 19:43:38 AEST 1990


In article <amoss.653145372 at shum> amoss at huji.ac.il (Amos Shapira) writes:
>FILE *
>memopen (cp, len)
>char *cp;
>int len;
>{
>  FILE *fp;
>
>  if ((fp = (FILE *)malloc(sizeof(*fp))) == NULL)
>    return (NULL);
>
>  fp->_bufsiz = fp->_cnt = len;
>  fp->_base = fp->_ptr = (unsigned char *)cp;
>  fp->_flag = (short)_IOREAD   _IOSTRG;
>
>  return (fp);
>}

Notes:
	1. SysV stdio does not have a _bufsiz field.  (The buffer
	   `size' is found by a bletcherous hack: if fp->_file is
	   not equal to NOFILE, it uses _bufendtab[fp->_file],
	   otherwise it assumes that the highest legal user-space
	   address is 0x7fffffff.  This is HORRIBLE.)
	2. 4.[0123]BSD stdio never tests _IOSTRG.
	3. _base and _ptr point to `char', not unsigned char, in
	   many stdios.
	4. 4.4BSD stdio does not have any of these fields.  (The FILE
	   structure contains the following fields:
		_p _r _w _flags _file _bf._base _bf._size _lbfsize
		_cookie _read _write _seek _close _ub._base _ub._size
		_up _ur _ubuf[] _nbuf[] _lb._base _lb._size _blksize
		_offset
	   _p corresponds closely to _ptr, _r and _w to _cnt, and
	   _bf to _base and _bufsiz.  _flags holds similar flags
	   to _flag, but there are differences.  One of _r and _w
	   is always 0, so that getc and putc always work.  Other
	   stdio getc's and putc's mysteriously fail if you switch
	   from reading to writing and forget to fseek.)

== GIANT CAVEAT		***WARNING***		DANGER WILL ROBINSON
== ALL OF THE APPROACHES BELOW except fmemopen/funopen WILL FAIL IF THE
== CODE CALLS setbuf OR setvbuf.

If you want to read a memory region using the V7/4BSD stdio, try:

	fp->_ptr = addr;	/* possibly with (unsigned char *) cast */
	fp->_cnt = nbytes;
	fp->_flag = _IOSTRG;	/* make _filbuf return error */

Under SysV, you are in trouble.  You can fopen /dev/null for reading
and replace _ptr and _cnt; this is likely to work.

Under 4.4BSD, use fmemopen (if we put it back in) or funopen and setvbuf
(which is how fmemopen is implemented).
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 405 2750)
Domain:	chris at cs.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.unix.programmer mailing list