Hi i'm attempting here to let a user select the id of a record he/she wishes to modify, find that record and allow the user to modify the record. this is as far as i got, after i locate the record and try to display it i get gibbrish as output and when i input the new data is doesnt write to the file. any suggestions will be appreciated.
I'm new to random access files so i'm pretty much going trial and error with my code.

void modify()
{
	Menu m;
	fstream modify;
	int id;

	modify.open("Inventory.dat", ios::out | ios::binary); //is ios::out correct?
	if(modify.fail())
	{
		cout<<"Inventory failed to open!\n";
		exit(1);
	}

	cout<<"Enter the id of the record you wish to delete: ";
	cin>> id;

	modify.seekg(id * sizeof(Menu));
	modify.read(reinterpret_cast<char*>(&m), sizeof(Menu));//find record     

	//displays the record specified by the id
	cout<<setw(4) << m.idNum << setw(25) << left << m.foodItem << m.price <<   m.description <<endl;

	
	cout << "\nEnter the new record you wish to overwrite this one with. "<<endl;
	cin.ignore();
	cout <<"\n\nID: ";
	cin >> m.idNum;

	cout << "Food item: ";
	cin.ignore();
	cin.getline(m.foodItem, 25, '\n');
	
	cout << "Price: ";
	cin >> m.price;
	
	cout << "Description: ";
	getchar();
	cin.getline(m.description, 60, '\n');
		
	modify.seekp(id * sizeof(Menu), ios::cur);
	modify.write(reinterpret_cast<const char*>(&m), sizeof(Menu));
	modify << m.idNum << m.foodItem << m.price << m.description <<endl;

	modify.close();

	system("pause");
	system("cls");
	displayMenu();

}//end modify()
Member Avatar for GreenDay2001

After taking a quick look to your code, the problem is here in line

modify.open("Inventory.dat", ios::out | ios::binary);

To read a file, you have to add ios::in flag as well. Hence that line should read,

modify.open("Inventory.dat", ios::in | ios::out | ios::binary);

WOW that simple huh, thank you very much that took care of the issue. Much thanks!

I also had to change this line from:

modify.seekp(id * sizeof(Menu), ios::cur);

To this:

modify.seekp(id * sizeof(Menu), ios::beg);

It wasnt overwriting the data due to that mistake

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.