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