Help! Deleting all contents!

I'm trying to create a function that will search for a specific record and delete it, but my function is deleting all the contents of the file. I can't figure out which line in the code is incorrect. Please help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
void Delete(fstream &file,fstream &file2, PayInfo &employee)
{
     int idnum;
            
     file.open("employees.dat", ios::in | ios::binary);
     file2.open("employees2.dat", ios::out | ios::binary);
     
     cout << "\nEnter the ID# of the employee you want to delete: " << endl;
     cin >> idnum;
    
     file.read(reinterpret_cast<char*>(&employee),sizeof(employee));
     
     while(!file.eof())
     {
          if (*employee.nameId.id == idnum)
          {
                 file2.write(reinterpret_cast<char*>(&employee),sizeof(employee));
          }
     
     file.read(reinterpret_cast<char*>(&employee),sizeof(employee));
    
     }
     
     file.clear();
     file.close();
     file2.clear();
     file2.close();
     

     file2.open("employees2.dat", ios::in | ios::binary);
     file.open("employees.dat", ios::out | ios::binary | ios::trunc);
     //file.clear();
     //file.close();
      
     file.open("employees.dat", ios::out | ios::binary);
     file2.read(reinterpret_cast<char*>(&employee),sizeof(employee));  
     
     while(!file2.eof())
     {
          cout << employee.nameId.fullname << employee.nameId.id << employee.hourlyRate;
          file.write(reinterpret_cast<char*>(&employee),sizeof(employee));
          file2.read(reinterpret_cast<char*>(&employee),sizeof(employee));
          
     }

     file.clear();   
     file2.clear();
     file.close();
     file2.close();

     file2.open("employees2.dat", ios::out | ios:: binary | ios::trunc);
     
     cout << "The record has been deleted." << endl;
     file2.clear();
     file2.close();
}
Don't you think accessing the file directly could be complicated? You can put the content of the data file in some data structure, then process, before writing back to the file.
Also opening one file simultaneously is not a good idea. Finish with one, maybe inputting into your app, then call the close() method, before opening for output.

Aceix.
Topic archived. No new replies allowed.