35

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?

4

8 Answers 8

30

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.

3
25

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/

7
  • 6
    It is worth mentioning that there might be issues with tmpfile() and tmpnam() in some contexts e.g., codeproject.com/KB/web-security/TemporaryFileSecurity.aspx
    – jfs
    Commented Jun 20, 2009 at 23:06
  • 4
    Tmpfile, of course, has the problem of returning a C file handle, not a c++ stream.
    – rlbond
    Commented Jun 21, 2009 at 0:43
  • 2
    @rlbond: Indeed, thats why I included tmpnam.
    – Tom
    Commented Jun 21, 2009 at 0:44
  • 4
    it's very important to note that tmpnam() is not to be used. its man page says: "Never use this function. Use mkstemp(3) or tmpfile(3) instead." Commented Apr 16, 2015 at 14:28
  • Where exactly is the temporary file created?
    – Ryuu
    Commented May 4, 2018 at 9:05
6

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

6

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.
1
3

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.

1
  • 4
    That's probably because the OP asked for a temporary file, and there are no standard C++ mechanisms for creating a unique filename. There is nothing in libstdc++ or boost that truly replaces mkstemp().
    – Tom
    Commented Jun 20, 2009 at 22:34
2

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.

1

A clean, portable and non-deprecated way of creating a temporary file is provided by Boost:

auto temporary_file = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.