rockoder
rockoder

Reputation: 747

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.

Upvotes: 3

Views: 3685

Answers (5)

Ionut Anghelcovici
Ionut Anghelcovici

Reputation:

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).

Upvotes: 3

njsf
njsf

Reputation: 2739

#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

Upvotes: 0

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247919

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.

Upvotes: 4

kbyrd
kbyrd

Reputation: 3351

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

Upvotes: 1

Marko
Marko

Reputation: 31375

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

Upvotes: 1

Related Questions