我可以使用CreateFile,但强制句柄到一个std :: ofstream?

有没有办法利用Win32 API中的文件创build标志,如FILE_FLAG_DELETE_ON_CLOSEFILE_FLAG_WRITE_THROUGH ,如http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx所述 ,但是然后强制该句柄成std :: ofstream?

与stream媒体的接口显然是平台独立的; 我想强制一些依赖于平台的设置在“引擎盖下”。

可以将C ++ std::ofstream附加到Windows文件句柄。 以下代码在VS2008中起作用:

 HANDLE file_handle = CreateFile( file_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (file_handle != INVALID_HANDLE_VALUE) { int file_descriptor = _open_osfhandle((intptr_t)file_handle, 0); if (file_descriptor != -1) { FILE* file = _fdopen(file_descriptor, "w"); if (file != NULL) { std::ofstream stream(file); stream << "Hello World\n"; // Closes stream, file, file_descriptor, and file_handle. stream.close(); file = NULL; file_descriptor = -1; file_handle = INVALID_HANDLE_VALUE; } } 

这适用于FILE_FLAG_DELETE_ON_CLOSE ,但是FILE_FLAG_WRITE_THROUGH可能没有预期的效果,因为数据将被std::ofstream对象缓冲,而不是直接写入磁盘。 但是,当stream.close()时,缓冲区中的任何数据都将刷新到操作系统。

其中一些标志在使用_fsopen / fopen时也是可用的:

 FILE* pLockFile = _fsopen(tmpfilename.c_str(), "w", _SH_DENYWR ); if (pLockFile!=NULL { // Write lock aquired ofstream fs(pLockFile); } 

在这里,我们打开文件,所以当做一个刷新,然后它通过(并closures时被删除):

 FILE* pCommitFile = fopen(tmpfilename.c_str(), "wcD"); if (pCommitFile!=NULL) { // Commits when doing flush ofstream fs(pCommitFile); }