c++ - How to create a std::ofstream to a temp file? -


OK, mkstemp is the preferred way of creating a temp file in POSIX.

But this opens the file and returns a int , which is a file descriptor, I can only create * FILE, but any std :: ofstream < / Code> No, which I like in C ++ (apparently, on Ax and some other systems, you can create std :: ofstream from a file descriptor, but when I try My compiler complains.)

I can get a temporary filename with tmpnam . And can open its own streams with it, but it is clearly unsafe due to the circumstances, and results in a compiler warning (on G ++ v3.4. Linux):

 < Code> Warning: Use of 'tmpnam' is dangerous, better use `mkstemp ' 

Therefore, there is no portable way to create a std :: offstream a temporary In the file?

I think this should work:

  four * Tmpname = strdup ("/ tmp / tmpfileXXXXXX"); Offstream f; Int fd = mkstemp (tmpname); F.attach (FD);  Edit:  OK, it can not be portable if you can not use attachments and do not make an ostream directly from a file descriptor. You can do this, then: 

  char * tmpname = strdup ("/ tmp / tmpfileXXXXXX"); Mkstemp (tmpname); Offstream F (TMPNA); As  mkstemp  creates a file for you, the position of the race should not be a problem here. 


Comments