Tutorial :tempnam equivalent in C++


I need to generate random names which I'll be using to create temporary files in a directory. Currently I am using C standard function tempnam() for this. My code is in C++ and would like to use C++ equivalent for doing the same task. The code needs to work on Solaris as well as on Windows.

Is anyone aware of such thing in C++? Any pointer on this would be highly appreciated.


Try std::tempnam in the cstdio header. ;)

The C standard library is still available in C++ code. For convenience, they provide C++ wrappers (in headers with the 'c' prefix, and no extension), and available in the std namespace.

You can also use the plain C version (stdio.h and tempnam in the global namespace, but you did ask for the C++ version ;))

The C++ standard library only provides new functions when there's actually room for improvement. It has a string class, because a string class is an improvement over char pointers as C has. It has a vector class, because, well, it's useful.

For something like tempnam, what would C++ be able to bring to the party, that we didn't already have from C? So they didn't do anything about it, other than making the old version available.


I know this doesn't answer your question but as a side note, according to the man page:

Although tempnam(3) generates names that are difficult to guess, it is nevertheless possible that between the time that tempnam(3) returns a pathname, and the time that the program opens it, another program might create that pathname using open(2), or create it as a symbolic link. This can lead to security holes. To avoid such possibilities, use the open(2) O_EXCL flag to open the pathname. Or better yet, use mkstemp(3) or tmpfile(3).


Why not just using the same function you are currently using in C? C++ is backward compatible with C.


What's wrong with tempnam()? You can use regular libc function right? tempnam is in stdio.h, which you're likely already including.


#include <cstdio>  using std::tmpnam;  using std::tmpfile;  

You should also check this previous question on StackOverflow and avoid race conditions on creating the files using mkstemp, so I would recommend using std::tmpfile

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »