Alternating between reading and writing repeatedly

Viewed 79

My objective is to read a file line by line, check if that line contains some number, and if so rewrite that line. Then continue reading the file. I've successfully been able to do this for one line, but I can't figure out how to continue reading the rest of the file. Here's how I replace one line (every line is a known fixed size):

while(getline(fs, line)){
  if(condition){
    pos = fs.tellg();       //gets current read position (end of the line I want to change)
    pos -= line.length()+1;    //position of the beginning of the line
    fs.clear();             //switch to write mode
    fs.seekp(pos);          //seek to beginning of line
    fs << new_data;         //overwrite old data with new data (also fixed size)
    fs.close();             //Done.
    continue;
  }
}

How do I switch back to read and continue the getline loop?

1 Answers
Related