我正在编写一个将结构写入二进制文件的程序,然后为用户提供编辑文件的选项。然后程序应该重写文件中写入原始结构的那个部分。代码:
struct Record
{
char name [16];
char phoneNum [16];
float balance;
};
int edit ( fstream& ref)
{
char searchVal[16];
cout << "Enter customer name: ";
cin.ignore();
cin.getline(searchVal, sizeof(searchVal));
int position = -1;
Record buffer;
bool found = false;
while(!ref.eof() && !found)
{
position = ref.tellg();
ref.read(reinterpret_cast<char*>(&buffer), RECORD_SIZE);
if((strcmp(buffer.name,searchVal) == 0))
{
found = true;
cout << buffer.name << " found! " << endl;
cout << "Enter new customer name: ";
cin.getline(buffer.name, sizeof(buffer.name));
cout << "Enter new customer phone number: ";
cin.getline(buffer.phoneNum, sizeof(buffer.phoneNum));
cout << "Enter new customer balance: ";
cin >> buffer.balance;
ref.seekg(-(RECORD_SIZE), ios::cur);
ref.write(reinterpret_cast<char*>(&buffer), RECORD_SIZE);
position = ref.tellp();
break;
}
}
if(!found)
{
cout << "Record not found" << endl;
}
ref.clear();
ref.seekg(0L, ios::beg);
return position;
}
基本上,找到记录并且用户可以“编辑”它,但它写在文件的末尾,我不知道为什么。感谢您在这方面的帮助。