views:

1196

answers:

7

Hi,

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?

Thanks.

edit: 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?

+1  A: 

http://www.cplusplus.com/doc/tutorial/files/

spitfire
So the open command will try to open the file and then create it if it doesn't exist?
Dave
Yes, thats right Meir. If the file doesn't exist, it will be created - an empty file for the sake of accuracy.
Elitecoder
+8  A: 

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/

Tom
Looks great. Thanks. I'm trying it out...
Dave
It is worth mentioning that there might be issues with tmpfile() and tmpnam() in some contexts e.g., http://www.codeproject.com/KB/web-security/TemporaryFileSecurity.aspx
J.F. Sebastian
Tmpfile, of course, has the problem of returning a C file handle, not a c++ stream.
rlbond
@rlbond: Indeed, thats why I included tmpnam.
Tom
@j.f sebastian. Nice article, thanks. Reading it.
Tom
+2  A: 

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.

Jonathan Leffler
+5  A: 

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 got 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.

Dave Rigby
The Linux man page for mkstemp(3) says that the last 6 characters in filename must be XXXXXX. See http://www.kernel.org/doc/man-pages/online/pages/man3/mkstemp.3.html
J.F. Sebastian
Hmm, the OS X manpage for mkstemp says you can have a variable number of XXXs. however in the interests of clarity (and 'cos most people are probably using Linux) I've changed the above example.
Dave Rigby
A: 

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.

Elitecoder
+1  A: 

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.

the_drow
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
+2  A: 

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

Vector Maniac