windows 我可以使用 CreateFile,但将句柄强制转换为 std::ofstream 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/475853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I use CreateFile, but force the handle into a std::ofstream?
提问by Steve Folly
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/en-us/library/aa363858(VS.85).aspx,然后强制将句柄转换为 std::ofstream?
The interface to ofstream is obviously platform independent; I'd like to force some platform dependent settings in 'under the hood' as it were.
ofstream 的接口显然是平台无关的;我想在“幕后”中强制一些平台相关的设置。
回答by ChrisN
It is possible to attach a C++ std::ofstream
to a Windows file handle. The following code works in VS2008:
可以将 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;
}
}
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. Any data in the buffer will be flushed to the OS when stream.close()
is called, however.
这适用于FILE_FLAG_DELETE_ON_CLOSE
,但FILE_FLAG_WRITE_THROUGH
可能不会达到预期的效果,因为数据将由std::ofstream
对象缓冲,而不是直接写入磁盘。但是,缓冲区中的任何数据都会在stream.close()
调用时刷新到操作系统。
回答by Rolf Kristensen
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);
}