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;
}
}
解决方案
您将所有内容都写入文件的开头,因此多个写入当然会相互覆盖。
您需要定义一种可以包含多条记录的文件格式,以及一种查找写入不与先前记录重叠的新记录的位置的方法,以及一种查找现有记录位置的简单方法。
您是否考虑过只使用 SQL(或其他类型)数据库?
推荐阅读
- node.js - 无法安装 vue-cli 因为 npm 问题的无限循环
- php - Twitter API 在文本末尾隐藏 URL
- laravel - 如何在 Laravel 的多对多多态关联中返回模型
- python - 是否可以在 Python 3 中创建一个前面带有 0 的十进制变量?
- c - C中未定义的函数引用
- c# - 如何派生引用时生成的对象并仍然更新基础?
- bash - Bash,csv文件:按列名获取行数
- python - 在具有特定列的for循环中将df附加到另一个df?
- php - Laravel 无法连接到 MySQL8 (AWS RDS)
- reactjs - getAccount() 是否足以使用 MSAL 通过 Azure AD B2C 保护 React SPA