[英]Can I use CreateFile, but force the handle into a std::ofstream?
Is there any way to take advantage of the file creation flags in the Win32 API such as FILE_FLAG_DELETE_ON_CLOSE
or FILE_FLAG_WRITE_THROUGH
as described here http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx , but then force that handle into a std::ofstream? 是否有任何方法可以利用Win32 API中的文件创建标志,例如
FILE_FLAG_DELETE_ON_CLOSE
或FILE_FLAG_WRITE_THROUGH
,如此处http://msdn.microsoft.com/zh-cn/library/aa363858(VS.85).aspx所述 ,然后强制该句柄进入std :: ofstream?
The interface to ofstream is obviously platform independent; 与ofstream的接口显然是平台无关的; I'd like to force some platform dependent settings in 'under the hood' as it were.
我想在“幕后”中强制某些平台相关的设置。
It is possible to attach a C++ std::ofstream
to a Windows file handle. 可以将C ++
std::ofstream
附加到Windows文件句柄。 The following code works in VS2008: 以下代码可在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;
}
}
This works with FILE_FLAG_DELETE_ON_CLOSE
, but FILE_FLAG_WRITE_THROUGH
may not have the desired effect, as data will be buffered by the std::ofstream
object, and not be written directly to disk. 这适用于
FILE_FLAG_DELETE_ON_CLOSE
,但FILE_FLAG_WRITE_THROUGH
可能无法达到预期的效果,因为数据将由std::ofstream
对象缓冲,而不直接写入磁盘。 Any data in the buffer will be flushed to the OS when stream.close()
is called, however. 但是,当
stream.close()
时,缓冲区中的所有数据都将刷新到操作系统。
Some of these flags are also available when using _fsopen / fopen: 当使用_fsopen / fopen时,其中一些标志也可用:
FILE* pLockFile = _fsopen(tmpfilename.c_str(), "w", _SH_DENYWR );
if (pLockFile!=NULL
{
// Write lock aquired
ofstream fs(pLockFile);
}
Here we open the file so when doing a flush, then it writes through (And it is deleted when closed): 在这里,我们打开文件,以便在进行刷新时写入(并在关闭时删除):
FILE* pCommitFile = fopen(tmpfilename.c_str(), "wcD");
if (pCommitFile!=NULL)
{
// Commits when doing flush
ofstream fs(pCommitFile);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.