当我试图从文件中读取时,访问冲突写入位置错误
Access violation writing location error when i try to read from file
这是我写入文件的地方->
void Supermarket_Billing_System::Add_and_WriteNewProduct(Product P)
{
ofstream fl;
fl.open("ProductList", ios::out | ios::binary);
fl.write((char *) &P, sizeof(P));
fl.close();
}
这是我从文件中读取的地方->
void Supermarket_Billing_System::Read_DisplayProductFromProductList()
{
Product P;
int x;
ifstream fp;
fp.open("ProductList", ios::in);
fp.seekg(0, ios::beg);
fp.read((char *) &P, sizeof(P));
x = P.GetProduct_qty();
fp.close();
}
产品类如下->
class Product
{
private:
long int Product_no;
std::string Product_name;
double Product_price;
int Product_qty;
double Product_tax;
double Product_dis;
public:
//Constructor
Product();
Product(long int, string, double, int, double, double);
//All Getters methods
long int GetProduct_no();
string GetProduct_name();
double GetProduct_price();
int GetProduct_qty();
double GetProduct_tax();
double GetProduct_dis();
//All Setters methods
void SetProduct_no(long int);
void SetProduct_name(string);
void SetProduct_price(double);
void SetProduct_qty(int);
void SetProduct_tax(double);
void SetProduct_dis(double);
void Accept_Product();
void Accept_ProductForBilling();
void Display_Product();
};
当我尝试通过调用Read_DisplayProductFromProductList()从文件中读取时,它给了我错误->
Supermarket_Billing_System.exe中0x6803ad54 (msvcp100 .dll)的未处理异常:0xC0000005:访问违规写入位置0xfeeefee .
由于std::string
成员,您的Product
类不容易复制;您不是在写入方法中写入Product_name
所持有的实际字符串,而只是std::string
的二进制表示形式,并且在读取时,内部字符串指针几乎肯定会指向无效位置。无论哪种方式,尝试按字节顺序复制非平凡可复制类都是未定义的行为。
你也没有通过binary
标志,当你打开你的文件读取
fp.open("ProductList", ios::in);
如果您正在读取的文件中有任何rn (0x0A 0x0D)序列,则会在Windows上导致问题。
你要么需要为你的字符串使用char
数组,要么手动处理每个成员的序列化。最简单的方法是使用流友元函数将对象写入纯文本文件
我认为您不应该像读取POD那样读取std::string(普通旧数据)。std::string Product_name
是Product
类的成员,当您从流中读取时,它可能会破坏字符串。
同样,你不应该这样写std::string
(作为Product
的一部分)。
当我在gSOAP客户机中使用ofstream对文件写操作时,我遇到了类似的问题。然而,当我切换到FILE (stdio.h)和fwrite()访问违规错误消失了!
可能是因为打开文件错误。您可以打印返回值来查看它是否为NULL。在编译代码时。
请注意警告信息。有时,它可能只是在编译器时发出警告,但在运行它时却崩溃了。
- 使用 EvtSetChannelConfigProperty() 函数时出现访问冲突错误
- cv::resize() 失败并出现访问冲突错误(由 NULL> 处的 <struct 引起)
- 将 std::string 作为参数从一个 DLL 传递到另一个 DLL 引发访问冲突错误
- 遵循官方 Direct2D 示例,但出现访问冲突错误
- C++ 抛出读取访问冲突错误,但我不确定为什么。平铺滑块益智游戏
- 为什么我的顶点缓冲区对象出现访问冲突错误?
- 销毁 Box2D 主体 - 读取访问冲突错误
- 编译哈希算法时出现内存访问冲突错误
- 使用glCreateBuffers时发生访问冲突错误
- 访问冲突错误在 (而 (info[x] != ))
- 反转字符串 c++ 时出现访问冲突错误
- 我无法弄清楚此访问冲突错误.有人可以在这里帮助我吗?
- 使用内存访问冲突错误
- 读取字符串的字符时出错-访问冲突错误C++
- 创建链接列表时发生访问冲突错误
- 调试优先级队列程序时出现访问冲突错误
- C++LinkedList错误:访问冲突错误
- 为什么我在用SDL2_ttf填充文本时出现访问冲突错误
- MFC:在工作线程中使用对象的成员函数时获取访问冲突错误
- 在C++中使用Box2D物理退出游戏时出现访问冲突错误