情况:
使用API对话框。当您单击鼠标左键时,会创建一个对话框,您可以在其中决定要保存到文件中的值,当您按“确定”按钮时,它将保存到二进制文件中。然后对话框关闭。
对话框关闭后,右键读取保存的文件。
问题:文件一创建,我就可以毫无问题地读取它。然而,在OpenFile()中,函数完成后出现以下错误。
发生异常(0x00403CEC,example.exe):0xC0000005:读取位置 0x0081F674 时发生访问冲突。 引发了未处理的异常:读取访问冲突。 _Pnext 是 0x5A1CE4。
我知道当您尝试访问您无权访问的内存区域时会发生该错误。为什么会出现这个问题呢?代码如下。
typedef struct
{
int ID_Name;
int ID_Emotiation;
string str;
}CCharacter_Script;
void myDebugMsg(const char* format, ...)
{
#ifdef _DEBUG
char str[128];
va_list args;
va_start(args, format);
vsprintf(str, format, args);
OutputDebugString(str);
va_end(args);
#endif
}
void Save(int nameID, int emotationID, char script[])
{
CCharacter_Script character;
character.ID_Name = nameID;
character.ID_Emotiation = emotationID;
character.str = script;
FILE* fp, * op;
fp = fopen("Save_Script.bin", "rb");
if (fp == NULL)
{
fp = fopen("Save_Script.bin", "wb");
fwrite(&character, sizeof(CCharacter_Script), 1, fp);
fclose(fp);
}
else
{
fclose(fp);
op = fopen("Save_Script.bin", "ab");
fwrite(&character, sizeof(CCharacter_Script), 1, fp);
fclose(op);
}
}
void OpenFile()
{
CCharacter_Script character;
FILE* fp;
int r_count;
fp = fopen("Save_Script.bin", "rb");
if (fp == NULL)
{
OutputDebugString("Error :: None File\n");
}
else
{
OutputDebugString("Reading :: Script\n");
// Continue repeating until you reach the end of the file
while ((r_count = fread(&character, sizeof(CCharacter_Script), 1, fp)) > 0)
{
myDebugMsg("Name: %d Emotation: %d\n '%s'\n", character.ID_Name, character.ID_Emotiation, character.str.c_str());
}
fclose(fp);
}
}
在“save()”函数中,您尝试以“追加二进制模式”打开文件进行写入,但在关闭初始文件指针后,您使用指针“fp”而不是“op”。
尝试使用 save() 函数
void Save(int nameID, int emotationID, char script[])
{
CCharacter_Script character;
character.ID_Name = nameID;
character.ID_Emotiation = emotationID;
character.str = script;
FILE* fp, * op;
fp = fopen("Save_Script.bin", "rb");
if (fp == NULL)
{
fp = fopen("Save_Script.bin", "wb");
fwrite(&character, sizeof(CCharacter_Script), 1, fp);
fclose(fp);
}
else
{
fclose(fp);
op = fopen("Save_Script.bin", "ab");
fwrite(&character, sizeof(CCharacter_Script), 1, op); // Use 'op' instead of 'fp'
fclose(op);
}
}