File descriptors and streams and co

Chris Torek chris at mimsy.UUCP
Thu Apr 27 11:50:24 AEST 1989


In article <1239500006 at osiris.cso.uiuc.edu>
hamilton at osiris.cso.uiuc.edu writes:
>void fexchange(a, b)
>FILE *a;
>FILE *b;
>{
>	FILE tmp;
>
>	tmp = *a;
>	*a = *b;
>	*b = tmp;
>}

This is not a good idea.  Consider the following (legal) extraction
from a hypothetical implementation of stdio:

stdio.h:
	typedef struct _file {
		int	putc_freespace;
		int	getc_unconsumed;
		unsigned char *putc_ptr;
		unsigned char *getc_ptr;
		unsigned char *buffer;
		int	bufsize;
		int	flags;
	} FILE;

	FILE	_iob[20];

	#define	stdin (&_iob[0])
	#define	stdout (&_iob[1])
	#define	stderr (&_iob[2])

	#define	fileno(fp) ((fp) - _iob)

The result of fexchange(stdin, f), in this implementation, is to replace
the counts and pointers for file descriptor 0 (stdin) with those for
file descriptor fileno(f) such that when stdin->getc_unconsumed (copied
from f->getc_unconsumed) goes to zero, the program reads from file
descriptor 0 ... stdin!

The only reason fexchange() works in existing stdio implementations is
that they happen to store the file descriptor in the FILE structure
(rather than making it implicit, as above).  Some SysV implementations
store some of their information outside the FILE structure, however,
making this doubly dangerous.  (Storing important information outside
the FILE objects is not illegal, merely stupid.)
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris at mimsy.umd.edu	Path:	uunet!mimsy!chris



More information about the Comp.lang.c mailing list