如何将 BSTR 编码写入文件?
我有一个将 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
BSTR 是宽字符 (wchar_t) 字符串。使用
WriteFile
等通用函数将它们写入文件应该没有问题。您遇到的唯一问题是使用某些文本编辑器查看文件。要解决这个问题,您必须在文件开头放置一个字节顺序标记 (BOM) ,在编写实际内容之前。这将向文本编辑器指示文件的内容。但请注意,当您读取文件内容时,您必须注意这一点 - 它将在文本之前包含该 BOM。您可以按照以下方式执行某些操作(未选中):
在创建文件之后、写入 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):
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 ofwchar_t
s, 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.