Tutorial :How to create a temporary text file in C++?



Question:

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?


Solution:1

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/


Solution:2

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.


Solution:3

This may be a little off-topic because the author wanted to create a tmp.txt and delete it after using it, but that is trivial - you can simple open() it and delete it (using boost::filesystem of course).

mkstemp() is UNIX-based. With Windows you use GetTempFileName() and GetTempPath() to generate a path to a temp file. Sample code from MSDN:

http://msdn.microsoft.com/en-us/library/aa363875%28VS.85%29.aspx


Solution:4

On Linux (starting with kernel 3.11), there's flag to open(2) O_TMPFILE that creates a temporary file that doesn't have a name (i.e. it doesn't show up in the filesystem). This has a few interesting features:

  • No worries about unique names, it's just an inode, there is no name.
  • No race conditions during creation (e.g. symlink attacks).
  • No stray files if your app crashes, it's always automatically deleted.


Solution:5

If you need a named file (for example, so you can pass the name to another process, perhaps a compiler or editor), then register a cleanup function that removes the file with atexit(). You can use either C++ <iostream> or C FILE * (<cstdio>) to create the file. The not completely standard but widely available mkstemp() function creates a file and tells you its name as well as returning a file descriptor (a third I/O mechanism); you could use the fdopen() function to convert the file descriptor into a FILE *.

If you don't need a named file a C-style FILE * is OK, then look at tmpfile() as suggested by @Tom.


Solution:6

I wonder why most of you guys showed him the C way of doing it instead of the C++ way.
Here's fstream.
Try that, deleting a file is OS depended but you can use boost.filesystem to make things easy for you.


Solution:7

Well, assuming you have been successful in creating the temporary file, you can use the remove function to delete it.

The function is declared in stdio.h -

#include <stdio.h>    int remove(const char *pathname);  

For example, if you want to delete a file named myfile.txt the code will be

#include<stdio.h>    int main()  {    if(remove("myfile.txt") == -1)    {      fprintf(stderr,"Remove failed");      exit(EXIT_FAILURE);    }    exit(EXIT_SUCCESS);  }  

I hope by now, you already know how to create the temp file, so this should resolve your query. Hope it helps.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »