[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: temp files under C



On Tue, Jun 26, 2001 at 03:21:52PM +1000, Brian May wrote:

> what is the safest way to open/create a temporary file under C, and
> get a string with the filename?
> 
> So far, I have seen:
> 
> tmpfile        looks ok, but how do I get the filename?

It doesn't have one, at least not for long.  The file is opened and immediately
unlinked, so it will be freed when the file descriptor is closed.

> mkstemp        returns a file handle, but I want a FILE*.
>
> so, at the moment mkstemp combined with fdopen looks the most hopeful.
> Is this the best way?

Yes, that is the best way to get a FILE*.

> However, that man page says:
> 
>        Don't use this function, use tmpfile(3) instead. It's bet­
>        ter defined and more portable.
> 
> :-(

It's right.  mkstemp(3) is in SUSv2, though, so it's not as if it's too much of
an oddball.

> ...also I assume (hope!) that mkstemp doesn't delete the file when it
> is closed. Is this correct?

Yes.  If the file is meant to stay around after you close it, though, perhaps
you should reevaluate your reasons for using a "temporary" file.  If the point
is to allow it to be opened by another program, pass the file descriptor to it
instead.  tmpfile(3) should be enough for most uses.

-- 
 - mdz



Reply to: