将cstring转换为byte并将其存储在本地文件中。 [英] Converting cstring to byte and store it in a local file.
本文介绍了将cstring转换为byte并将其存储在本地文件中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I want to convert the cstring to bytes and store it in a local file with size.
The following code does not help. Just open the file and the string text is saved.
我尝试过:
What I have tried:
CString str = "I am not sure that this method is right or not. Anyone can tell me how to convert a CString to BYTE* ?";
BYTE *pByte;
int length = str.GetLength();
pByte = new BYTE[length + 1];
memcpy(pByte, (VOID*)LPCTSTR(str), length);
str.ReleaseBuffer();
FILE *fp;
if (fp = fopen("C:\\Users\\user\\mui0n.txt", "wb")) {
fwrite(&length, sizeof(int), 1, fp);
fwrite(pByte, length, 1, fp);
}
fclose(fp);
delete[] pByte;
推荐答案
如果您需要存储CString对象以供日后检索,我建议您使用 MFC中的序列化| Microsoft Docs [ ^ ]。
那就是说,在你的代码中你打电话给str.ReleaseBuffer()
尽管你没有打电话给str.GetBuffer()
并且,无论如何你可以写的是
If you need to store the CString object for later retrieval I sugggest you using Serialization in MFC | Microsoft Docs[^].
That said, in your code you are callingstr.ReleaseBuffer()
despite you didn't callstr.GetBuffer()
and, in any case you could have written instead
CString str = "I am not sure that this method is right or not. Anyone can tell me how to convert a CString to BYTE* ?";
FILE *fp;
if (fp = fopen("C:\\Users\\user\\mui0n.txt", "wb")) {
fwrite(&length, sizeof(int), 1, fp);
fwrite((PCTSTR)str, length, sizeof(TCHAR), fp);
}
fclose(fp);
这篇关于将cstring转换为byte并将其存储在本地文件中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文