如何将 BSTR 编码写入文件?

发布于 2024-12-10 11:57:55 字数 573 浏览 0 评论 0原文

我有一个将 BSTR 写入文件的函数,但我无法将其写入包含编码的文件?这是我的功能,请指正!

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海里的那抹蓝 2024-12-17 11:57:55

BSTR 是宽字符 (wchar_t) 字符串。使用 WriteFile 等通用函数将它们写入文件应该没有问题。您遇到的唯一问题是使用某些文本编辑器查看文件。要解决这个问题,您必须在文件开头放置一个字节顺序标记 (BOM) ,在编写实际内容之前。这将向文本编辑器指示文件的内容。但请注意,当您读取文件内容时,您必须注意这一点 - 它将在文本之前包含该 BOM。

您可以按照以下方式执行某些操作(未选中):

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

在创建文件之后、写入 BSTR 内容之前。

迟来的补充,只是为了澄清我的第一句话:BSTR不完全是一个wchar_t数组,而是为了编写其内容对于一个文件,可以这样对待它。有关详细信息,请阅读 Eric 的 BSTR 语义完整指南< /a>.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文