[英]read access violation while reading file with ifstream
我正在尝试将矢量保存到文件中并将其读回。 我设法保存它,但是当我尝试加载它时,我得到 1 个元素,然后出现错误。 如果我通过将元素加载到缓冲区中来跳过它(注释代码),我设法正确加载下一个。 当循环体结束时,我得到了错误。 我尝试使循环独立于 steram,但仍然出现错误。 我的加载方法是
void Load() {
//cars is private vector
cars.empty();
lastIndex = 0;
ifstream f(path.c_str());
if (f.fail())
return;
//while (f.peek() != EOF) {
while (true) {
//char* buffer = new char[sizeof(CarInfo)];
//f.read(buffer, sizeof(CarInfo));
CarInfo car = CarInfo(&f);
if (car.ID() > lastIndex)
lastIndex = car.ID();
//Add is public method to add items in cars
Add(car);
}
f.close();
}
我的保存方法
void Save() {
ofstream f(path.c_str());
for (int i = 0; i < cars.size(); i++) {
cars[i].Write(&f);
}
}
我的 class
class CarInfo
{
public :
int ID() { return id; }
string Color() { return color; }
string Brand() { return brand; }
double Price() { return price; }
void Discount() { price = price - price * .1; }
void Read(ifstream* in) { in->read((char*)this, sizeof(CarInfo)); }
void Write(ofstream* out) { out->write((char*)this, sizeof(CarInfo)); }
CarInfo(int ID,string Color,string Brand,double Price) {
if (Color.find_first_not_of(' ') == std::string::npos)
throw invalid_argument("Invalid Color!");
if (Color.length() > 20)
throw invalid_argument("Color too long!");
if (Brand.find_first_not_of(' ') == std::string::npos)
throw invalid_argument("Invalid Brand!");
if (Brand.length() > 20)
throw invalid_argument("Brand too long!");
if (Price < 0)
throw std::invalid_argument("Invalid Price!");
id = ID;
color = Color;
brand = Brand;
price = Price;
}
CarInfo(ifstream* in) { Read(in); }
CarInfo() { id = -1; color = "not set"; brand = "not set";price = 0;}
private:
int id;
string color;
string brand;
double price;
};
错误是
抛出异常:读取访问冲突。 _Pnext 是 0x6BD974。
在第 1293 行的“xrmemory”中。如果有更好的方法可以做到这一点,我愿意接受建议。 该任务只说将其保存为单个二进制文件
我设法使它工作,但我仍然想知道为什么第一个不起作用。 这是我的解决方案...
while (f.peek() != EOF) {
char* buffer = new char[sizeof(CarInfo)];
f.read(buffer, sizeof(CarInfo));
CarInfo *car = (CarInfo*)(buffer);
Add(CarInfo(car->ID(),car->Color(),car->Brand(),car->Price()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.