tandaica0612
tandaica0612

Reputation: 371

Write BSTR to file with encoding how to?

I have a function to write file a BSTR, but I can not write it to a file with encoding include? Here is my function, please correct for me!

unsigned long Vnpt_WriteFile(const LPCTSTR pFilePath, const BYTE* pbData, const DWORD cbData)
{
    DWORD numbytes = 0;
    unsigned long rv = 0;
    FILE*   fileHandle;

    HANDLE fh = CreateFile(pFilePath, FILE_WRITE_DATA,0,NULL,CREATE_ALWAYS,0,NULL);
    if (fh == INVALID_HANDLE_VALUE){
        rv = CKR_CREATE_FILE_ERROR;
        return rv;
    }

    if(!WriteFile(fh, pbData, cbData, &numbytes, NULL)){
        rv = CKR_WRITE_FILE_ERROR;
    }
    CloseHandle(fh);
    return rv;
}

Upvotes: 0

Views: 1582

Answers (1)

Eran
Eran

Reputation: 22030

BSTR are wide char (wchar_t) strings. You should have no problem writing them into a file using general purpose functions as WriteFile. Only problem you'll have is with viewing the file with some text editor. To solve that, you have to place a Byte Order Mark (BOM) at the beginning of the file, before you write the actual content. This will indicate the file's content to text editor. Note, however, that you'll have to be aware of that when you read the file's content - it will contain that BOM before the text.

You can do something along these lines (unchecked):

unsigned char BOM[2] = {0xFF, 0xFE};
WriteFile(fh, BOM, 2, &numbytes, NULL);

right after you create the file, and before you write the BSTR's content.

Late addition, just to clarify my first sentence: a BSTR is not exactly an array of wchar_ts, but for the sake of writing its content to a file, it is ok to treat it as such. For more on this, read Eric's Complete Guide To BSTR Semantics.

Upvotes: 1

Related Questions