Visual Studio's version of std::ifstream
has a non-standard constructor and a non-standard open()
overload that both have an extra optional _Prot
parameter for specifying "file protection/sharing flags" (see _fsopen()
for the list of available flags). However, delete
sharing is not one of supported flags.
There is an alternative, though. Visual Studio's version of both std::ifstream
and std::ofstream
have non-standard constructors that accept a FILE*
for the file access. You can wrap a HANDLE
from CreateFile()
into a FILE*
using Microsoft's _open_osfhandle()
and _fdopen()
functions, for example (error handling removed for brevity):
Can I use CreateFile, but force the handle into a std::ofstream?
HANDLE file_handle = CreateFile(...,FILE_SHARE_DELETE,...);
int file_descriptor = _open_osfhandle((intptr_t)file_handle, _O_RDONLY);
FILE* file = _fdopen(file_descriptor, "r");
std::ifstream stream(file);
...
// Closes stream, file, file_descriptor, and file_handle.
stream.close();
If you need something more portable to non-Microsoft compilers, you will likely have to resort to writing a custom std::basic_streambuf
class (or maybe derived from std::filebuf
) to wrap your HANDLE
, and then pass an object of that class to the std::basic_istream
constructor directly.