cancelling fdopen(3)

David C. Miller, consultant dcm at sfsup.UUCP
Fri Dec 12 23:41:52 AEST 1986


In article <88 at dcl-csvax.comp.lancs.ac.uk> Stephen J. Muir writes
that he:

    needs to open file descripter
    allocate FILE structure
    work with it
    then deallocate struct w/o closing fd

In article <169 at its63b.ed.ac.uk> S Brown CS replies:
>Well, the easiest way would be to put
>	FILE *f_fd = fdopen (dup(fd), "w");
>and then you can release the FILE * structure with fclose(f_fd),
>which will close only the dup of fd, not fd itself.
>

The one thing I'd add is this:

    fflush(f_fd);
    lseek(fd, lseek(fileno(f_fd), 0, 1), 0);

x = fileno(f_fd)	gives the file descriptor used by f_fd
x = lseek(x, 0, 1)	gives the offset of that file descriptor
lseek(fd, x, 0)		sets the offset of fd to be that of f_fd

This way fd is at the expected position in the file.
Now some one is going to say:

    You can simplify that by saying:
	lseek(fd, ftell(f_fd), 0)

Don't do it, it is not guaranteed portable.  The old manuals
said it nicely:
	"It is measured in bytes on UNIX;
	on some other systems it is a magic cookie"
				fseek(3) BSD 4.2 Manual

and you can't lseek to a magic cookie 8-).

				Dave

--

David C. Miller, consultant
AT&T Information Systems
190 River Road
Summit, NJ  07901
(201) 522-5149

{allegra,burl,cbosgd,clyde,ihnp4,ulysses}!sfsup!dcm



More information about the Comp.unix.wizards mailing list