Monday, August 9, 2010

using tmpnam is dangerous. Use mkstemp

Whenever I used tmpnam my g++ compiler cribbed that its dangerous to use tmpnam and must use mkstemp. But mkstemp returned file id and as my language is C++, i never knew how to use the C file ids with C++ fstreams. Then I found out from the man page of fstream that,


explicit basic_ofstream(int fd);
explicit basic_ofstream(const char *s,
ios_base::openmode mode =
ios_base::out,
long protection = 0666);

I was familiar with the second usage but the first usage was new to me...So one can easily use ofstream with mkstemp as shown below.

char *tmpFileName= strdup("/tmp/tmpfileXXXXXX");
if(mkstemp(tmpFileName) == -1)
throw runtime_error("temporary file cannot be created");
ofstream out(tmpFileName);

Enjoy C++

No comments: