0
#include <fstream>
#include <string>
#include <iostream>
#include <stdio.h>
using namespace std;
class Car {
 private:
  string carNm;
  char carNum[20];

 public:
  void getCarData() {
    cout << "car Name: ";
    cin >> carNm;
    cout << "car Number: ";
    cin >> carNum;
    cin.ignore();
  }
  void displayCarData() {
    cout << "\nCar Name: " << carNm;
    cout << "\nCar Number: " << carNum;
    cout << "\n-----------------------------------------------\n";
  }
  int storeCar();
  void viewAllCars();
};

int Car::storeCar() {
  if (carNm == "" && carNum == "") {
    cout << "car data not initialized";
    return 0;
  }
  ofstream f;
  f.open("car.txt", ios::out | ios::app);
  f.write((char*)this, sizeof(*this));
  f.close();
  return 1;
}
void Car::viewAllCars() {
  ifstream fin;
  fin.open("car.txt", ios::in | ios::app);
  if (!fin) {
    cout << "File not found";
  } else {
    fin.seekg(0);
    fin.read((char*)this, sizeof(*this));

    while (!fin.eof()) {
      displayCarData();
      fin.read((char*)this, sizeof(*this));
    }
    fin.close();
  }
}
int main() {
  Car c;
  c.getCarData();
  c.storeCar();
  c.viewAllCars();
  system("PAUSE");
  return 0;
}

Error Message: Unhandled exception at 0x0fabad7a (msvcp100d.dll) in file2.exe: 0xC0000005: An access violation occurred while loading location 0x00214afc.

what could be causing this error? Storing data into file works fine. However this happens while reading from the file. I am using Visual studio 2010.

David G
  • 94,763
  • 41
  • 167
  • 253
Amresh
  • 11
  • 3
  • 2
    `sizeof(*this)` will be a ***constant*** size of this class, with a `carNm` `std::string`. And it's a compile-time constant that will be ***the same*** whether `carNm` is an empty string, or contains everything in Encyclopedia Brittanica. if you ponder on that fact, the reason for the segfault should become immediately obvious. Sorry, C++ does not work this way. You need to write your own code to serialize/deserialize these objects. – Sam Varshavchik Feb 19 '20 at 02:18
  • Reading a class from a file like that is only allowed if the class is trivially copyable. `string` is not trivially copyable, and `Car` contains `string`, so `Car` isn't trivially copyable either. – Joseph Sible-Reinstate Monica Feb 19 '20 at 02:21

0 Answers0