当我试图从文件中读取时,访问冲突写入位置错误

Access violation writing location error when i try to read from file

本文关键字:访问冲突 错误 位置 读取 文件      更新时间:2023-10-16

这是我写入文件的地方->

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_nameProduct类的成员,当您从流中读取时,它可能会破坏字符串。

同样,你不应该这样写std::string(作为Product的一部分)。

当我在gSOAP客户机中使用ofstream对文件写操作时,我遇到了类似的问题。然而,当我切换到FILE (stdio.h)和fwrite()访问违规错误消失了!

可能是因为打开文件错误。您可以打印返回值来查看它是否为NULL。在编译代码时。

请注意警告信息。有时,它可能只是在编译器时发出警告,但在运行它时却崩溃了。