An access violation occurred while reading from file (C++)

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.

c++
visual-studio-2010
asked on Stack Overflow Feb 19, 2020 by Amresh • edited Feb 19, 2020 by 0x499602D2

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0