Problem: Your code needs to create a file (and perform write/read operations on it probably) during its execution. In many cases, there are two requirements.
1. It should be unique, which means that you do not want to overwrite any existing files. Sometimes you even want exclusive access to that file to avoid race conditions.
2. The file is no longer needed when the program is done, thus you need to clean up after yourself.
Solution: The problem is similar to the malloc() and free() problem, therefore it is not surprising to see a solution similar to alloca() and smart pointers. A tempfile is a file which will be automatically deleted when it is closed or the program terminates.
Short answer: tmpfile() is the way to go. It confirms to a bunch of standards, including 4.3 BSD/C89/C99/POSIX. When you do not want to have the file automatically deleted, use mkstemp() instead, which also gives you some control over the file name.
Long story:
mkstemp() and mktemp() will create a temporary file while DO NOT delete it automatically. Besides, on the manual page of mktemp(), it says "never use mktemp()" and suggests mkstemp() to avoid a race condition.
You may also use mkdtemp() to create a temporary directory. Again, the caveat is that mkdtemp() is similar to mktemp(), i.e. the directory does not get garbage collected automatically.
tempnam() and tmpname() create a name for a temporary file, which does not conflict with existing files. The catch is that on their manual pages, you will see the "never use this function" label and mkstemp() and tmpfile() are suggested here again.
Tips:
1. Always read the notes and bugs sections on the manual pages.
2. Check out related functions in the "see also" section on the manual pages. There may be a better choice among them.
Friday, June 26, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment