我可以使用CreateFile

我可以使用CreateFile

本文介绍了我可以使用CreateFile,但将句柄强制为std :: ofstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有任何方法可以利用Win32 API中的文件创建标志,例如 FILE_FLAG_DELETE_ON_CLOSE FILE_FLAG_WRITE_THROUGH 如此处所述,但然后强制该句柄成为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?

tostream的接口显然是平台独立的;

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\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()时,缓冲区中的任何数据都将刷新到操作系统。

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:46