Can I use CreateFile, but force the handle into a std::ofstream?

依然范特西╮ 提交于 2019-11-26 18:58:43

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;
        }
}

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.

Some of these flags are also available when using _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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!