Hello pro's,
I have a problem with this project I'm working on, the code involves searching for and replacing a structure in a binary file. I have written a similar (smaller) code that replicates the problem. This code will write 3 structures (each with only one int variable) to a binary file, It will then ask the user which number they want to search for and change, then display the new numbers. The problem with this code is the searching and changing part. I've tried so many different things and I'm at a stand still. If anyone has any advice to give it sure would be greatly appreciated. I've labeled what I'm certain is the problem code below.
#include <iostream>
#include <fstream>
usingnamespace std;
struct num
{
int number;
};
int main()
{
long pos;
int change_num;
num object;
// write three simply structures to the file
fstream open("number.dat", ios::out | ios::binary);
if(!open)
{
cout << "error opening file\n";
return 0;
}
for (int i = 0; i < 3; i++)
{
cout << "enter number for structure" << i+1 <<endl;
cin >> object.number;
open.write(reinterpret_cast<char *>(& object), sizeof(object));
}
open.close();
// now display all four
fstream look("number.dat", ios::in | ios::binary);
if (!look)
{
cout << "error opening file\n";
return 0;
}
look.read(reinterpret_cast<char *>(&object), sizeof (object));
while (!look.eof())
{
cout << object.number << endl;
look.read(reinterpret_cast<char *>(&object), sizeof(object));
}
look.close();
/******************************* PROBLEM CODE ***************************/
// now attempt to seach for a specific one and change it
cout << "\nenter a number to search for and change\n";
cin >> change_num;
fstream search_replace("number.dat", ios::in| ios::out | ios::binary);
if (!search_replace)
{
cout << "error opening file\n";
return 0;
}
search_replace.read(reinterpret_cast<char *>(&object), sizeof (object));
while (!search_replace.eof())
{
if (object.number == change_num)
{
pos = search_replace.tellp();
cout << "\nenter a new number for this position in the file\n";
cin >> object.number;
search_replace.seekp(pos,ios::beg);
search_replace.write(reinterpret_cast<char *>(&object), sizeof(object));
break;
}
}
search_replace.close();
/**********************************************************************/
// display the new list
fstream lookie("number.dat", ios::in | ios::binary);
if (!lookie)
{
cout << "error opening file\n";
return 0;
}
lookie.read(reinterpret_cast<char *>(&object), sizeof (object));
while (!lookie.eof())
{
cout << object.number << endl;
lookie.read(reinterpret_cast<char *>(&object), sizeof(object));
}
lookie.close();
}