In
for(int i=0;i<n;i++){
c=new Car(); (*c)=Enter(); c->Disp();
file.open("CARS.dat",ios::app|ios::binary);
file.write((char*)c , sizeof(*c)); delete c;
}
file.open("CARS.dat",ios::app|ios::binary);
открывает файл. Ничего не закрывает. Если вы открываете поток открытого файла, поток переходит в состояние ошибки и становится непригодным для использования до тех пор, пока эта ошибка не будет подтверждена и clear
ed.
При первом открытии файла, вероятно, он работает. Невозможно убедиться, что это сработало, потому что проверка не проводилась. Всегда подтверждайте, что транзакция ввода-вывода была успешной, прежде чем пытаться использовать результат транзакции.
Примечание. Чтобы предотвратить растягивание ответа, я здесь не имею дело с правильной сериализацией. Это покрыто в другом месте. Многие другие.
if(d=='1')
{
ofstream file("CARS.dat",ios::app|ios::binary); //allocate and open file
if (file.is_open())
{
cout<<"Enter Number:-"; cin>>n;
for(int i=0;i<n;i++){
car c = Enter(); // no need for dynamic allocation here.
c.Disp();
// serialize c to file here.
if (!(file))
{ // failed to write to file.
// handle error here as is appropriate for the program.
// the following notifies the user and then exits the program.
std::cerr << "Error writing Cars.dat\n";
return -1;
}
} // car c destroyed here free of charge
}
else
{
std::cerr << "could not open Cars.dat\n";
}
} // file closed and destroyed here.
else if(d=='2')
{
ifstream file("CARS.dat"); //allocate and open file for reading
if (file.is_open())
{
while(true) // loop FOREVER!!!! Muhuhahahahahahahaha!!!!!!
{
Car c;
//deserialize file into c
if (file) // read a Car
{
c.Disp(); // display it.
}
else
{
break; // OK. Not forever. Exit when we can't read a Car
}
}
}
else
{
std::cerr << "could not open Cars.dat\n";
}
}