我想将字符串以及许多其他数据存储在二进制文件中,我使用下面的代码(当我真正使用它时,字符串将是 malloc'd)我可以写入文件。我在十六进制编辑器中查看了它。我不确定我是否正确地编写了空终止符(或者如果我需要)。当我读回时,我得到的字符串长度与我存储的字符串长度相同,但不是字符串。我究竟做错了什么?
FILE *fp = fopen("mybinfile.ttt", "wb");
char drumCString[6] = "Hello\0";
printf("%s\n", drumCString);
//the string length + 1 for the null terminator
unsigned short sizeOfString = strlen(drumCString) + 1;
fwrite(&sizeOfString, sizeof(unsigned short), 1, fp);
//write the string
fwrite(drumCString, sizeof(char), sizeOfString, fp);
fclose(fp);
fp = fopen("mybinfile.ttt", "rb");
unsigned short stringLength = 0;
fread(&stringLength, sizeof(unsigned short), 1, fp);
char *drumReadString = malloc(sizeof(char) * stringLength);
int count = fread(&drumReadString, sizeof(char), stringLength, fp);
//CRASH POINT
printf("%s\n", drumReadString);
fclose(fp);