Data delete - fstream

Hi. this is part of my code where i would like to have some help. this code should contain part where you can delete entry in file but it works something like this right now it finds entry which i want to delete but also delete all other entries below the one i have selected.
But my goal here is to delete only the selected entry. Hope someone can 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
  void DeleteEntry()
{
     int temp;     
     clientData Dati;
     fstream fails2;     
     ifstream fails("DatuBaze.txt");     
     cout <<"Klienta konta Nr.\n";
     cin >>temp;
     
     do
     {  
     fails >> Dati.accNum >> Dati.Name >> Dati.Sur >> Dati.balance;
     fails2.open ("DatuBaze.txt",ios::out);          
           if(temp != Dati.accNum)
           {                    
           fails2 << Dati.accNum <<" "<<Dati.Name<<" "<<Dati.Sur<<" "<<Dati.balance<<endl;                               
           }
     }         
     while (!fails.eof());
          
     fails.close();
     fails2.close();
     main();              
     
}
What was your question? Was something not working?
Have you considered using a std::vector, read the file store the information in the vector, search through the vector, erase the desired element from the vector, then write out the "new" information back to the file.

Remember you can't really delete items from the middle of a text file, you can just overwrite the contents. And remember if you try to overwrite the contents the "new" data must have the exact same number of characters.

By the way why do you keep trying to open fails2 in your loop, without closing it first? What happens if the file fails to open?


1
2
3
4
5
6
std::ofstream fails2("foo.txt"); //open once, at construction time. Also, it is another file
while(fails >> Dati.accNum >> Dati.Name >> Dati.Sur >> Dati.balance){ //don't loop on eof, loop on the reading operation
  //...
}
rename("foo.txt", "DatuBaze.txt"); //when you end you move it
//no need to close, the destructor take care 

You may use a filename that you know that doesn't exists, but it may be better to generate one automatically.
There is the `tmpname()' function, but its usage is discouraged in favor of `tmpfile()', which returns a FILE*
¿Anyone knows a c++ alternative?
(An alternative to convert http://www.cplusplus.com/forum/general/63995/#msg346157 )


By the way, it's illegal to call `main()'
Last edited on
Topic archived. No new replies allowed.