使用 WriteFile API 将 unicode CString 写入文件
如何使用 WriteFile Win32 API 函数将 CString 实例的内容写入由 CreateFile 打开的文件?
请注意,不使用 MFC,而是通过包含“atlstr.h”来使用 CString
编辑:我可以做
WriteFile(handle, cstr, cstr.GetLength(), &dwWritten, NULL);
or 吗
WriteFile(handle, cstr, cstr.GetLength() * sizeof(TCHAR), &dwWritten, NULL);
?
How can I write contents of a CString instance to a file opened by CreateFile using WriteFile Win32 API function?
Please note MFC is not used, and CString is used by including "atlstr.h"
edit: Can just I do
WriteFile(handle, cstr, cstr.GetLength(), &dwWritten, NULL);
or
WriteFile(handle, cstr, cstr.GetLength() * sizeof(TCHAR), &dwWritten, NULL);
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于 ATL,它是这样的:
它是字节顺序标记 (BOM),它让记事本知道编码是 UTF-16。
With ATL it's like this:
It's byte order mark (BOM) which lets Notepad know that encoding is UTF-16.
您需要选择一种文本编码,将字符串转换为该编码,然后相应地写入文本文件。最简单的是 ANSI,因此基本上您可以使用
T2CA
宏将TCHAR
字符串转换为 ansi,然后将内容转储到文件中。类似于(未经测试/编译):因为它是 ANSI 编码,所以它只能在具有相同代码页设置的计算机上读取。要获得更便携的解决方案,请使用 UTF-8 或 UTF-16。
You need to pick a text encoding, convert the string to that encoding, and write the text file accordingly. Simplest is ANSI, so basically you would use the
T2CA
macro to convert yourTCHAR
string to ansi, then dump the contents in a file. Something like (untested/compiled):Because it's ANSI encoding though, it will only be readable on computers that have your same code page settings. For a more portable solution, use UTF-8 or UTF-16.
转换为 ANSI 可能会导致代码页出现问题,因此在许多情况下是不可接受的。下面是一个将 unicode 字符串保存到 unicode 文本文件的函数:
使用:
记事本可以识别 unicode 文本文件。
Converting to ANSI can cause problems with code pages, so it is not acceptable in many cases. Here is a function that saves unicode string to unicode text file:
Using:
Notepad understands unicode text files.
我相信你需要额外的铸造:
I believe you need additional casting:
还要确保在开头写入正确的字节顺序标记,以便记事本可以正确读取它。
Also make sure that you write proper byte order mark in the beginning so that Notepad can read it properly.