Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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;
Posted
Updated 22-Nov-17 21:56pm

1 solution

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 calling str.ReleaseBuffer() despite you didn't call str.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);
 
Share this answer
 
Comments
Chopin2001 23-Nov-17 8:21am    
Thanks CPallini.
CPallini 23-Nov-17 8:23am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900