tags:

views:

330

answers:

5

Hi,

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.

Regards, GP

+1  A: 

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

Dev er dev
+1  A: 

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

kbyrd
+4  A: 

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.

jalf
Take care to distinguish what is in `std` and what is not. It isn't safe to assume that if a function is in <stdio.h> then <cstdio> contains the same function in the `std` namespace. This is only true for functions that are in Annex C.2 of the Standard of which there are 209 of them in the 1998 standard. Anything else that might be in <stdio.h> may be visible when including <cstdio> but nothing guarantees that it is in the `std` namespace.
D.Shawley
true. I haven't checked where (and when) in the C standard tempnam is defined.
jalf
A: 
#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

njsf
+2  A: 

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