Let’s say I’m creating a program in C that needs to use a tempfile. Creating an ad hoc tempfile in /tmp is probably not a good idea. Is there a function or OS call to supply me with a tempfile name so that I can begin to write and read from it?
Share
You can use the
mkstemp(3)function for this purpose. Another alternative is thetmpfile(3)function. Which one of them you choose depends on whether you want the file to be opened as a C library file stream (whichtmpfiledoes), or a direct file descriptor (mkstemp). Thetmpfilefunction also deletes the file automatically when you program finishes.The advantage of using these functions is that they avoid race conditions between determining the unique filename and creating the file — so that two programs won’t try to create the same file at the same time, for example.
See the man pages for both functions for more details.