Click here to Skip to main content
15,943,753 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to edit and delete data in file(C/C++).

What I have tried:

I have tried this method
 ifstream read, read1;
ofstream write, write1;"File.txt", ios::in);"Temp.txt");

int old, New, a;
cout << "Enter number you want to edit = ";
cin >> old;

cout << "Enter new number to replace ";
cin >> New;

while (!read.eof()) {
    read >> a;

    if (a == old) { write << New << endl; }
    else          { write << a << endl;   }

write.close();"Temp.txt", ios::app);"File.txt");

while (!read1.eof()) {
    read1 >> a;
    write1 << a << endl;

And this code work well.
But the issue is that this process is very slow. I mean if there are thousand of lines in file and i want to edit or delete just one line then the process is very slow.
So i need some algorithm by using that i can able to edit or delete just that line i want.
So is there any algorithm or Function?

Updated 30-May-18 0:33am

You can avoid the second while loop which is just copying the content. Instead delete File.txt and then rename Temp.txt:
// Deleting the file is only necessary if the used C library 
//  implementation does not support renaming to an existing file
rename("Temp.txt", "File.txt");
That will make your application run about half the time of your code with large files.
Share this answer
I would do the following:

1) read the full file in a string
2) make than a string replace
3) and write the file

use std::string for supporting my plan ;-)
Share this answer
Usama Iftikhar Butt 30-May-18 11:32am    
can you explain your idea little bit more

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900