我一直在尝试从 C++ 中的二进制文件中读取数据,但出现运行时错误,程序已停止工作!
我以前使用过类似的代码,它仍然有效。在执行类 SettingsClass 的构造函数时出现错误 [可能是因为读取功能,因为删除它后,一切都运行良好。]
struct Setting{
int SettingID;
int SettingINTValue;
double SettingDOUBLEValue;
char SettingCHARValue;
string SettingSTRINGValue;
string SettingName;
};
class SettingsClass {
public:
void ResetSettings() {
fstream SettingFile;
Setting defaultsetting[NoOfSettings];
for(int i=1;i<=NoOfSettings;i++) {
defaultsetting[i-1].SettingID = i;
defaultsetting[i-1].SettingINTValue = 0;
defaultsetting[i-1].SettingDOUBLEValue = 0.0;
defaultsetting[i-1].SettingCHARValue = '#';
defaultsetting[i-1].SettingSTRINGValue = "null";
switch(i) {
default:
defaultsetting[i-1].SettingName = "Compression Levels";
defaultsetting[i-1].SettingSTRINGValue = "Normal";
defaultsetting[i-1].SettingINTValue = 1;
break;
}
cout<<i<<". "<<defaultsetting[i-1].SettingName<<"\n\t "<<defaultsetting[i-1].SettingINTValue<<"\n\t "<<defaultsetting[i-1].SettingDOUBLEValue<<"\n\t "<<defaultsetting[i-1].SettingCHARValue<<"\n\t "<<defaultsetting[i-1].SettingSTRINGValue<<"\n\t ";
cout<<"\n";
}
SettingFile.open(SettingsFilePath,ios::binary|ios::out);
if(SettingFile.is_open()){
SettingFile.write(reinterpret_cast<char const *>(&defaultsetting),sizeof(defaultsetting));
} else {
cout<<"Error!";
}
SettingFile.close();
}
SettingsClass() {
fstream SettingFile;
SettingFile.open(SettingsFilePath,ios::binary|ios::in);
if(SettingFile.is_open()) {
Setting TempSettings[NoOfSettings];
SettingFile.read((char*)&TempSettings,sizeof(TempSettings));
} else {
cout<<"Error...";
}
SettingFile.close();
}
} Settings;