0

I need to create a temporary file, fill it with some data and send the result to a function that accepts only std::istreams.

I tried using tmpfile() and it works for my first requirement - 'create a file and fill it with some data', but it returns a FILE* and there is no way to convert it (as far as I know) to std::streams.

Is there a C++ way of creating a temporary file? If this is not possible, how reliable is tmpnam to return a valid file name? Did anyone test this on Android or iOS?

EDIT: I don't want to copy the data to std::stringstream as a part of my test is reading the data from the disk.

Mircea Ispas
  • 20,260
  • 32
  • 123
  • 211

1 Answers1

2

If you want an alternative to std::tmpfile or std::tmpnam, you might want to look at the Boost Filesystem library. It contains a function unique_path() that will give you a place to put directories, files, etc.

It also includes other filesystem manipulation features that the standard library doesn't have, like iterating over files in a directory. I've found these especially useful for unit tests.

Steve
  • 6,334
  • 4
  • 39
  • 67
  • one should note that the use of boost::filesystem::unique_path() is discouraged, as is the use of the original C library calls: it poses a security risk. This is addressed in https://stackoverflow.com/questions/43316527/what-is-the-c17-equivalent-to-boostfilesystemunique-path -- in the end the way to handle these is to use calls that generate a filename and open it atomically, returning an open file pointer. – markgalassi Apr 17 '21 at 05:34