//-------------------------------------------------------------------
//-- Writing BSTR to a File C++ sample - davemoats.com
//--
//-- This sample is provided 'as-is', without any express or implied warranty.
//-- In no event will the authors be held liable for any damages arising from
//-- the use of this sample code.
//--
//-------------------------------------------------------------------

#define _UNICODE

#include <windows.h>

int wmain(int argc, wchar_t* argv[])
{
    DWORD dwRet = 0;

    // open the file
    HANDLE hUfile = CreateFile( L"test.out",
                                         GENERIC_WRITE,
                                         0,
                                         NULL,
                                         CREATE_ALWAYS,
                                         FILE_ATTRIBUTE_NORMAL,
                                         NULL );

    if( hUfile != INVALID_HANDLE_VALUE )
    {
        // allocate a BSTR
        BSTR bszVal = ::SysAllocString( L"Something to write to a file" );
        if (bszVal == NULL)
            return E_OUTOFMEMORY;
        else
        {
            // get the length of the BSTR - UNICODE so mult by 2
            DWORD dwBytes = 0;
            DWORD dwLen = ( ::SysStringLen( bszVal ) * 2 );


            if( !WriteFile( hUfile,
                                 bszVal,
                                 dwLen,
                                 &dwBytes,
                                 NULL ))
            {
                // no data written
                dwRet = GetLastError();
            }

            // free BSTR
            ::SysFreeString( bszVal );
        }

        // close file
        CloseHandle( hUfile );
    }
    else
    {
        // couldn't open the file
        dwRet = GetLastError();
    }

    return dwRet;
}


Copyright © 2005 - 2013 Dave Moats.  All rights reserved.  Links: Copyright © by their respective owners.
NO WARRANTIES EXTENDED.  Void where prohibited by law.  Please report any issues or broken links.
You may link to this site freely from your own site.  You may quote from this site, but please include a link to the original source on the originating site.