在文件中读取和写入多个结构

时间:2019-10-21 20:01:55

标签: c++

我正在尝试将多个结构存储到一个文件中,而我的问题是,当我尝试将2个结构添加到同一文件中时,我的第二个结构会覆盖我的第一个结构,而当我打印出第一个结构时,它的打印我的第二个结构。我想在文件中包含多个结构,以便一次可以显示一个结构,并且可以一次编辑一个结构。关于我的代码有什么问题的任何线索吗?

int main()
{
Record record1;
Record record2;
int choice;
int choice2;

cout << "Welcome to your Records! What do you want to do today?" << endl;
cout << endl << endl;



while(choice2 != -1)
{
    cout << " " << endl;
    cout << "1) Add new records to the file" << endl;
    cout << "2) Display any record in the file" << endl;
    cout << "3) Change any record in the file" << endl;
    cout << "4) Exit" << endl;
    cout << "Your Choice: ";
    cin >> choice;

    while(choice < 1 || choice > 4)
    {
        cout << "Invalid choice! Enter again" << endl;
        cin >> choice;
    }

    if(choice == 1)
    {
        ofstream outFile("RecordFile.dat", ios::out | ios::binary);
        AddItem(outFile);
        outFile.close();

    }
    else if(choice == 2)
    {
        ifstream inFile("RecordFile.dat",ios::out | ios::binary);
        DisplayItem(inFile);
        inFile.close();

    }
    else if(choice == 3)
    {
        ofstream outFile("RecordFile.dat", ios::out | ios::binary);
        EditItem(outFile);
        outFile.close();
    }

    else if(choice == 4)
    {
        choice2 = -1;
    }

}

return 0;
}

头文件

struct Record
{
char  name[15];
int quantity;
double wholesalecost;
double retailcost;
};

void AddItem(ofstream& outFile);
void DisplayItem(ifstream& inFile);
void EditItem(ofstream& outFile);

功能

void AddItem(ofstream& outFile)
{
  Record record;

  cout << "What is the name of this record: ";
  cin.ignore();
  cin.getline(record.name,15);
  cout << "How many do we have(quantity): ";
  cin >> record.quantity;
  cout << "Whats the whole sale cost: ";
  cin >> record.wholesalecost;
  cout << "Whats the retail cost of " << record.name << ":";
  cin >> record.retailcost;

if(outFile)
{
    outFile.write((char*)&(record),sizeof(record));

}
else
{
    cout << "File not Found" << endl;
}
}

void DisplayItem(ifstream& inFile)
{
  Record record;
  int recordnum;
  cout << "Enter what record number you want to display " << endl;
  cin >> recordnum;
  recordnum--;

if(inFile)
{
    inFile.seekg(sizeof(Record) * recordnum, ios::beg);
    inFile.read(reinterpret_cast<char *>(&record), sizeof(record));

    cout << "Name: " << record.name << endl;
    cout << "Quantity: " << record.quantity << endl;
    cout << "Whole Sale Cost: " << record.wholesalecost << endl;
    cout << "Retail Cost: " << record.retailcost << endl;
}
else
{
    cout << "File not found" << endl;
}
}

1 个答案:

答案 0 :(得分:0)

您正在将所有内容写入文件的开头,因此,当然,多次写入会相互覆盖。

您需要定义一种文件格式,其中可以包含多个记录,并提供一种方法来查找与以前的记录不重叠的新记录的写入位置,以及一种查找现有记录位置的简便方法。

您是否考虑过仅使用SQL(或其他类型的)数据库?