0

我一直在尝试从 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;
4

1 回答 1

1

您应该阅读并了解有关文件流以及相关的输入和输出运算符<<>>. 您不能像这行代码那样简单地将字符输入到数组中:

SettingFile.read((char*)&TempSettings,sizeof(TempSettings)); 

该数组不是,char但您将其转换为这样。相反,您应该遍历可用的输入并填写数组,例如:

for(size_t i = 0; i<NoSetting; ++i) {
  SettingFile >> TempSettings[i];
}

当然,您应该重载适当的输入运算符:

istream& operator>>(istream& _is, Setting& _s) {
  //read all variables of setting, i.e.:
  //_is >> _s.var1;
  //_is >> _s.var2;
  //etc.
}

您的输出可能有相同的错误。你应该重载:

ostream& operator<<(ostream& _os, const Setting& _s) {
  //output all variables of Setting, e.g.:
  //_os << _s.var1;
}

做这样的事情而不是 filestream write

for(size_t i = 0; i<NoSetting; ++i) {
  SettingsFile << defaultSetting[i];
}
于 2013-10-21T18:09:23.673 回答