I'm trying to create a temporary text file in C++ and then delete it at the end of the program. I haven't had much luck with Google.
Could you tell me which functions to use?
The answers below tell me how to create a temp file. What if I just want to create a file (tmp.txt) and then delete it? How would I do that?
In C Programming Language, the tmpfile() function is used to produce/create a temporary file. tmpfile() function is defined in the “stdio. h” header file. The created temporary file will automatically be deleted after the termination of program. It opens file in binary update mode i.e., wb+ mode.
If successful, tmpfile() returns a pointer to the stream associated with the file created. If tmpfile() cannot open the file, it returns a NULL pointer. On normal termination (exit()), these temporary files are removed.
Syntax : char *tmpnam(char *str) s : The character array to copy the file name. It generates and returns a valid temporary filename which does not exist. If str is null then it simply returns the tmp file name.
Maybe this will help
FILE * tmpfile ( void );
http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/
Open a temporary file
Creates a temporary binary file, open for update (wb+ mode -- see fopen for details). The filename is guaranteed to be different from any other existing file. The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally.
See also
char * tmpnam ( char * str );
Generate temporary filename
A string containing a filename different from any existing file is generated. This string can be used to create a temporary file without overwriting any other existing file.
http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/
Here's a complete example:
#include <unistd.h> int main(void) { char filename[] = "/tmp/mytemp.XXXXXX"; // template for our file. int fd = mkstemp(filename); // Creates and opens a new temp file r/w. // Xs are replaced with a unique number. if (fd == -1) return 1; // Check we managed to open the file. write(fd, "abc", 4); // note 4 bytes total: abc terminating '\0' /* ... do whatever else you want. ... */ close(fd); unlink(filename); // Delete the temporary file. }
If you know the name of the file you want to create (and are sure it won't already exist) then you can obviously just use open
to open the file.
tmpnam
and tmpfile
should probably be avoided as they can suffer from race conditions - see man tmpfile(3)
for the details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With