Quote Originally Posted by Lindley View Post
Another option would be to read the first object from the ifstream, then read the remainder of the file into a string, then use tmpfile() to generate a temporary file. fwrite() the string into the temporary file, seek back to the beginning, and proceed to read it.

I'm not sure if the temporary file would be in memory or on disk, though. If it's in memory then the inefficiency essentially amounts to a couple of extra copies. If it's on disk, this is probably not ideal.
I'm pretty sure tmpfile opens a file on disc. You just have the guarantee (kind of) that the file name will be unique and super complicated.

Also, If your file is something like 2GB, and you have interleaving C-C++ objects, then welcome to slow ville.

Here's a crazy idea. Start by reading the entire file into a stream, and then keep both open in parallel. Everytime you read from one, just advance by the same amount in the other. You'd have bit of space overhead, but you wouldn't be opening and closing your file every object read, nor copying all it's content to a temporary file every time.

This wouldn't work quite as well with write, but as already discussed, there are other alternatives for writing, and you rarelly need to mix read an write operations on the same file.