我在 AccountManagement.cpp 中有一个 AccountManagement 类。我在 Account.cpp 中有另一个名为 Account 的类。我有一个模板,它使用 OdereList 类对列表中的给定数据进行排序,该类也有自己的迭代器。 AccountManagement 类在二进制文件中输出帐户列表,如下所示:
void AccountManagement::saveData(const char * file) //saves data in the specified binary file
{
ofstream out(file, ios::out | ios::binary);
if(!out)
{
cerr<<"Problem opening output file!"<<endl;
}
OrderedList<Account>::iterator it = this->account_manager.begin();
for(int i = 0; i < this->total_accounts; i++)
{
Account temp = *it;
out.write((char*)&temp, sizeof(Account));
it++;
}
out.close();
}
我在 AccountManagement 类中定义了以下函数,它从二进制文件中读取所有数据并将其输出。这个功能工作得很好。它显示在这里:
void AccountManagement::output()
{
ifstream in("accounts.dat", ios::in | ios::binary);
if(!in)
{
cerr<<"File doesn't exist!"<<endl;
exit(1);
}
Account acc;
while(in.read((char*)&acc, sizeof(Account)))
{
cout<<acc;
}
in.close();
}
但是,当我在另一个文件中使用这个相同的函数(具有不同的名称)时,该文件也有 Account.h 头文件以及从同一个“account.dat”文件中检索数据时它给我段错误。可能是什么问题呢?以下是函数:
void loadData()
{
ifstream in("accounts.dat", ios::in | ios::binary);
if(!in)
{
cerr<<"File doesn't exist!"<<endl;
exit(1);
}
Account acc;
while(in.read((char*)&acc, sizeof(Account)))
{
cout<<acc;
}
in.close();
}
账户类声明:
class Account
{
friend ostream& operator<<(ostream&,const Account&); //overloading << operator
friend istream& operator>>(istream&,Account&); //overloading >> operator
public:
void operator=(const Account&); //overloading = operator
bool operator<=(const Account&); //overloading <= operator
bool operator<(const Account&); //overloading < operator
private:
string number; //Account Number
char name[100]; //Account holder's name
char sex; //M or F indicating the gender of account holder
MYLIB::Date dob; //date of birth of account holder
char address[100]; //address of account holder
char balance[20]; //balance of account holder
};
最佳答案
我不知道 MYLIB::Date
类,但是你有一个 std::string
对象就足够了。
std::string
对象动态分配内存以适应它包含的字符串。堆上分配的内存仅供当前进程使用,您不能保存指针(在 std::string
类中)并从其他进程加载它并希望有是该指针处的有效内存。
如果您在一个进程中保存指向动态分配内存的指针,并从另一个进程加载和使用它,那么您将有未定义的行为。
您需要serialize字符串以保存它。也可能是 MYLIB::Data
对象。
免责声明:它将在具有单一统一地址映射的小型嵌入式系统上工作,不幸的是,所有面向用户的操作系统(如 Windows、OSX 和 Linux)都有单独的地址空间和墙进程之间。
关于C++:从二进制文件读取输入时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547305/