Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a temporary file for writing in C++ on a Linux platform?

In C++, on Linux, how can I write a function to return a temporary filename that I can then open for writing?

The filename should be as unique as possible, so that another process using the same function won't get the same name.

like image 735
J Miller Avatar asked Oct 01 '08 22:10

J Miller


2 Answers

tmpnam(), or anything that gives you a name is going to be vulnerable to race conditions. Use something designed for this purpose that returns a handle, such as tmpfile():

   #include <stdio.h>

   FILE *tmpfile(void);
like image 91
twk Avatar answered Oct 21 '22 09:10

twk


Use one of the standard library "mktemp" functions: mktemp/mkstemp/mkstemps/mkdtemp.

Edit: plain mktemp can be insecure - mkstemp is preferred.

like image 35
nobody Avatar answered Oct 21 '22 07:10

nobody