問題描述
有什么方法可以利用 Win32 API 中的文件創建標志,例如 FILE_FLAG_DELETE_ON_CLOSE
或 FILE_FLAG_WRITE_THROUGH
,如此處所述http://msdn.microsoft.com/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 http://msdn.microsoft.com/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 嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!