简体   繁体   English

如何在读取文件时修复 c++ 上的分段错误(核心转储)错误?

[英]How to fix the segmentation fault(core dumped) error on c++ while reading the file?

When I tried to run this code on c++ 17 it worked but then on c++ it doesn't.当我尝试在 c++ 17 上运行此代码时,它可以工作,但在 c++ 上却没有。 While running the first time it just gives me the string value of the last entered elements but when I run it the second time it shows the segmentation fault(core dumped) error.第一次运行时,它只给了我最后输入元素的字符串值,但是当我第二次运行它时,它显示分段错误(核心转储)错误。 Can someone help me with this?有人可以帮我弄这个吗?

Here is my code:这是我的代码:

#include<iostream>
#include<string>
#include<fstream>
#include<vector>
#include<iomanip>
#include <stdlib.h>
using namespace std;
void show1(string name,string type,string price,string quantity){
  cout<<"=======================================\n";
  cout<<setw(5)<<name<<setw(15)<<type<<setw(10)<<price<<setw(15)<<quantity<<"\n";
  cout<<"========================================\n";
}
template<class T>
void Readfile(T &obj,string fname,string name,string type,string price,string quantity){
  int i=1;
  ifstream f;
  f.open(fname,ios::in);
  f.seekg(0);
  Display(name,type,price,quantity);
  while(!f.eof()){
    f.read((char*)&obj, sizeof(obj));
    
    if(!f.eof())      {
      if(f.tellg()<0)
        {   i=0; break;}
          obj.putdata();
     }
    }
        
  f.close();
}

class Items{
    string name;
    double price;
    int quantity;
    public:
    string itemObj;
        
    void getdata(string obj){
        cout<<"Enter name, price and quantity: \n";
        cin>>name>>price>>quantity;
        itemObj=obj;
    }
    void putdata(){
      cout<<setw(5)<<name<<setw(10)<<itemObj<<setw(12)<<price<<setw(10)<<quantity<<"\n";
    }
    
    void writeToFile(int n,string obj);
    void ReadFile_item();
    int check(string temp_name);
    void refill_Item(int qty);
    double checkout_price(int qty);

    
}item;

class CD:public Items{
 public:
  void Add_CD();
  
}cd;




double Items::checkout_price(int qty){
  if(quantity>=qty){
    quantity-=qty;
    cout<<"File Updated";
    return price*qty;
  }
  else{
    cout<<"\nNot enough stock";
    return 0;
  }
}  
void Items::writeToFile(int n,string obj){
    ofstream f;
    f.open("stock.txt",ios::out|ios::app);
       
    for(int i=0;i<n;i++){
      item.getdata(obj);
      f.write((char*)&item, sizeof(item));
      cout<<"File Updated\n";
    }
    f.close();
       
}

void Items:: ReadFile_item(){
   Readfile(item,"stock.txt","Name","Item type"," Price ","Available stock");
}



void Add_item_obj(string obj){
  int n;
  cout<<"Enter no. of "<<obj<<"'s to add: \n";
  cin>>n;
  item.writeToFile(n,obj);
}
void CD::Add_CD(){
  Add_item_obj("CD");
}



void main_menu(){
  int i=0;
  do{
    cout<<"============================\n";
    cout<<"-------MAIN MENU------------\n";
    cout<<"============================\n";
    cout<<"1. Sell Items\n";
    cout<<"2. Add Items\n";
    cout<<"4. View stock file\n";
    cout<<"5. Exit \n";
    
    cout<<"Enter your choice: ";
    cin>>i;

    switch(i){
      case 1: sell_items();
              break;
      
      case 2: writetoFile(1,"CD");
              break;

      case 3: item.ReadFile_item();
              break;

      

      default: cout<<"Exiting... \n";
                exit(0);
    }
  }while(i!=0);
}

int main(){
   main_menu();
    
    return 0;
}  
f.read((char*)&obj, sizeof(obj));

This cast is nonsensical.这个演员阵容很无厘头。 There are two ways to see why this can't possibly work:有两种方法可以查看为什么这不可能工作:

  1. Say obj is a std::string .obj是一个std::string This code must read a fixed number of bytes (otherwise, what is it passing to read ?).此代码必须读取固定数量的字节(否则,它传递给read的是什么?)。 But what number of bytes is sufficient for any possible contents of a string?但是对于字符串的任何可能内容,多少字节就足够了? Clearly, this can't possibly work.显然,这不可能奏效。 Whatever size gets passed to read , the string's logical can be larger than that.无论传递给read的大小是多少,字符串的逻辑都可以大于该大小。

  2. The contents of memory may contain information only meaningful in the context of the current process. memory 的内容可能包含仅在当前进程的上下文中有意义的信息。 For example const char *foo = "hello";例如const char *foo = "hello"; makes foo hold the address of the string constant "hello" .使foo保存字符串常量"hello"的地址。 What is the point of writing that address to a file?将该地址写入文件有什么意义? How would any subsequent execution of any subsequent process no what was stored at that particular address while this process was running?在该进程运行时,任何后续进程的任何后续执行都不会存储在该特定地址的内容?

Your code reads and writes the physical contents of objects to and from files.您的代码从文件中读取和写入对象的物理内容。 You need to read and write the logical contents of the objects, not the particular way those contents happen to be encoded in memory during this execution of this process.您需要读取和写入对象的逻辑内容,而不是在此过程执行期间这些内容碰巧在 memory 中编码的特定方式。

To use an analogy, I might remember a particular restaurant as "the place where I ate for my twentieth birthday".打个比方,我可能记得某家餐厅是“我二十岁生日吃饭的地方”。 But if I'm communicating that restaurant to someone else, telling them how I remember that restaurant isn't helpful.但是,如果我将那家餐厅传达给其他人,告诉他们如何记得那家餐厅并没有帮助。 I have to encode it in a way that I know they will understand.我必须以我知道他们会理解的方式对其进行编码。 That's what file formats do.这就是文件格式的作用。

To write data to a file, you have to decide on a file format and implement code to convert to and from that format.要将数据写入文件,您必须确定文件格式并实现代码以转换为该格式和从该格式转换。 For things like strings, you either have to decide on a maximum size you will support and always read and write that number of bytes or use some format that permits a variable size.对于字符串之类的东西,您要么必须决定将支持的最大大小并始终读取和写入该字节数,要么使用允许可变大小的某种格式。

Have a look at well-known file formats with existing libraries.使用现有库查看众所周知的文件格式。 Text is easiest, but there's also things like XML and JSON.文字最简单,但也有 XML 和 JSON 之类的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM