我可以使用 CreateFile,但将句柄强制转换为 std::ofstream 吗?

编程入门 行业动态 更新时间:2024-10-07 13:22:24
本文介绍了我可以使用 CreateFile,但将句柄强制转换为 std::ofstream 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有什么方法可以利用 Win32 API 中的文件创建标志,例如 FILE_FLAG_DELETE_ON_CLOSE 或 FILE_FLAG_WRITE_THROUGH,如此处所述msdn.microsoft/en-us/library/aa363858(VS.85).aspx ,然后将该句柄强制转换为 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 msdn.microsoft/en-us/library/aa363858(VS.85).aspx , but then force that handle into a std::ofstream?

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.

推荐答案

可以将 C++ std::ofstream 附加到 Windows 文件句柄.以下代码适用于 VS2008:

It is possible to attach a C++ std::ofstream to a Windows file handle. The following code works in 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 "; // 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() 时,缓冲区中的任何数据都将刷新到操作系统.

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.

更多推荐

我可以使用 CreateFile,但将句柄强制转换为 std::ofstream 吗?

本文发布于:2023-11-02 07:03:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:句柄   可以使用   转换为   ofstream   CreateFile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!