c++ - How to update data at a particular line in a file? -


consider have following file ("testt.txt")

abc 123 def 456 ghi 789 jkl 114 

now if wanted update figure next name ghi (i.e. 789), how it?

the following code helps me reach there no doubt, how update quickly?

#include<iostream> #include<fstream> #include<string>  using namespace std;  int main()  {     int counter = 0;     string my_string;     int change = 000;     ifstream file ( "testt.txt" );      while(!file.eof())     {         counter = counter + 1;         getline(file, my_string, '\n');         if (my_string == "ghi")          {             ofstream ofile ( "testt.txt" );             (int = 0; < counter + 1; i++)             {                 //reached line required i.e. 789                 //how process here?             }             ofile.close();             break;         }     }     cout << counter << endl;     file.close();     return 0; } 

clearly counter here 5 corresponding "ghi", counter + 1 point value 789. how change 000?

------------solved-----------final code------

 #include<iostream>  #include<fstream>  #include<string>  #include <cstdio>  using namespace std;  int main()  { string x; ifstream file ( "testt.txt" ); ofstream ofile ( "test2.txt" ); while (!file.eof()) {     getline(file,x);     if (x == "789")     {         ofile << "000" << endl;     }     else         ofile << x << endl; } file.close(); ofile.close(); remove("testt.txt"); return 0; } 

output ("test2.txt")

abc 123 def 456 ghi 000 jkl 114 

if open file ifstream reading, , ofstream writing, ofstream either not work or overwrite file - not sure option right, neither want.

so use std::fstream open file reading , writing:

fstream file ( "testt.txt" ); 

after arriving proper place, use seekp method enable writing stream after reading (it works without seekp, when fails, bug difficult find), required standard:

if (my_string == "ghi")  {     file.seekp(file.tellg());     ...     break; } 

when modifying files, have replace existing bytes new ones. it's important write 3 bytes, value 789 overwritten properly. may want check range:

if (change < 0 || change > 999)     abort(); // or recover error gracefully 

and set width of output field before writing it:

file << setw(3) << change; 

if code switches writing reading, use file.seekg(file.tellp()) ensure works properly.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -