I am a newbie and quite new to programming. I am trying to update records in a binary file. I program on Turbo C++. The program does not update the records.
When I read from the file after updation, it displays the original records and goes in an infinite loop.
// This is the Structure 'product' whose instances I have written to the file
struct product
{
int code;
char description[20];
int stock;
};
// This is the function which updates the data
void update(fstream &file)
{
product p;
cout<<"\nENTER THE OLD PRODUCT CODE OF THE RECORD YOU WANT TO UPDATE\n";
int c;
cin>>c;
while(file.read((char *)&p,sizeof(p)))
{
if(p.code == c)
{
file.seekg(-sizeof(p),ios::cur);
clrscr();
cout<<"\nMATCH FOUND\n";
getch();
clrscr();
cout<<"\nENTER THE NEW DESCRIPTION\n";
gets(p.description);
cout<<"\nENTER THE NEW STOCK QUANTITY\n";
cin>>p.stock;
file.write((char *)&p,sizeof(p));
}
}
}
The last version of Turbo C++ was from a decade ago, I strongly recommend you use a newer IDE and compiler. On Windows I recommend Visual Studio 2015 or later.
The way you are writing the file is wrong - you should never directly write the memory of a struct in a file because different compilers and even different settings in the same compiler can change the padding of the structure in incompatible ways. You need to use serialization instead - that means manually writing and reading the elements of the structure to guarantee they are handled properly. To avoid endianness issues, I recommend using a text-only format, not a binary format.
Check the return value at lines 21 and 30. My guess is that one of them is failing. Is the open for reading and writing? If it's only open for reading then line 30 will fail, the current position in the file will be at the current record, and you'll read it again at line 17, resulting in an infinite loop.
@dhayden
I checked the return value at line 21. You were right. The pointer was not placed at correct position. I tried it the other way round and it worked. Thanks. But one thing I want to ask is that why wasn't the Pointer being placed at the correct position?. Please kindly help.