Don't manipulate the input file while you are reading from it. Write your changes to a new file first, and then replace the original file with the new file only if everything is successful.
Also, you are reading each record in the file into this
, which is just bad design, and will potentially corrupt this
. More importantly, you did not show the declaration of person
, but based on your description, it sounds like person
contains data members that simply can't be read/written as-is and will need additional serialization. For instance, char*
/std::string
strings (flat char[]
arrays are OK).
Also, you are not incrementing count
if the requested Id
is found, but you are checking if count
has been incremented when the loop is finished.
Also, your code lacks adequate error handling.
Try something more like this instead:
#inlcude <fstream>
#include <cstdio>
...
bool readPerson(std::istream &in, person &p)
{
// do whatever is needed to de-serialize a person record *properly*...
return in.read(reinterpret_cast<char*>(&p), sizeof(p));
}
bool writePerson(std::ostream &out, const person &p)
{
// do whatever is needed to serialize a person record *properly*...
return out.write(reinterpret_cast<char*>(&p), sizeof(p));
}
void person::edit_teacher(char *Id)
{
std::ifstream infile("TeachersRecord.txt");
if (!infile)
{
std::cout << "Can't open File to read." << std::endl;
}
else
{
std::ofstream outfile("TeachersRecord_new.txt");
if (!outfile)
{
std::cout << "Can't create File to write." << std::endl;
}
else
{
bool found = false;
person p;
while (readPerson(infile, p))
{
if ((!found) && (strcmp(Id, p.id) == 0))
{
found = true;
std::cout << "\n\t\t\t*********Enter new record********" << std::endl << std::endl;
p.setData();
*this = p;
}
if (!writePerson(outfile, p))
{
outfile.close();
std::remove("TeachersRecord_new.txt");
std::cout << "Can't write to File." << std::endl;
return;
}
}
if (!infile.eof())
{
std::cout << "Can't read from File." << std::endl;
return;
}
infile.close();
outfile.close();
if (!found)
{
std::remove("TeachersRecord_new.txt");
std::cout << "Record is not found." << std::endl;
}
else if (std::rename("TeachersRecord.txt", "TeachersRecord_bak.txt") != 0)
{
std::remove("TeachersRecord_new.txt");
std::cout << "Can't Backup File." << std::endl;
}
else if (std::rename("TeachersRecord_new.txt", "TeachersRecord.txt") != 0)
{
std::rename("TeachersRecord_bak.txt", "TeachersRecord.txt");
std::remove("TeachersRecord_new.txt");
std::cout << "Can't replace File." << std::endl;
}
else
{
std::remove("TeachersRecord_bak.txt");
std::cout << "Record is Successfully Updated." << std::endl;
}
}
}
}