Alternating between reading and writing

My goal is to read the file line by line, check whether this line contains any number, and if so, rewrite this line. Then continue reading the file. I was successfully able to do this for one line, but I cannot figure out how to continue reading the rest of the file. Here, as I replace one line (each 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 go back to reading and continue the getline loop?

+4
source share
1 answer

, TB-scale, . , , , ( ), , .

:

#include <iostream>
#include <fstream>
using namespace std;

bool CreateDummy()
{
  ofstream out;
  out.open("Dummy.txt");
  // skip: test if open

  out<<"Some Header"<<endl;
  out<<"REPLACE1  12345678901234567890"<<endl;
  out<<"REPLACE2  12345678901234567890"<<endl;
  out<<"Now ~1 TB of data follows..."<<endl;

  out.close();

  return true;
}


int main()
{
  CreateDummy(); // skip: test if successful

  fstream inout;
  inout.open("Dummy.txt", ios::in | ios::out);
  // skip test if open

  bool FoundFirst = false;
  string FirstText = "REPLACE1";
  string FirstReplacement = "Replaced first!!!";

  bool FoundSecond = false;
  string SecondText = "REPLACE2";
  string SecondReplacement = "Replaced second!!!";

  string Line;
  size_t LastPos = inout.tellg();
  while (getline(inout, Line)) {
    if (FoundFirst == false && Line.compare(0, FirstText.size(), FirstText) == 0) {
      // skip: check if Line.size() >= FirstReplacement.size()
      while (FirstReplacement.size() < Line.size()) FirstReplacement += " ";
      FirstReplacement += '\n';

      inout.seekp(LastPos);
      inout.write(FirstReplacement.c_str(), FirstReplacement.size());
      FoundFirst = true;
    } else if (FoundSecond == false && Line.compare(0, SecondText.size(), SecondText) == 0) {
      // skip: check if Line.size() >= SecondReplacement.size()
      while (SecondReplacement.size() < Line.size()) SecondReplacement += " ";
      SecondReplacement += '\n';

      inout.seekp(LastPos);
      inout.write(SecondReplacement.c_str(), SecondReplacement.size());
      FoundSecond = true;
    }

    if (FoundFirst == true && FoundSecond == true) break;
    LastPos = inout.tellg();
  }
  inout.close();

  return 0;
}

Some Header
REPLACE1  12345678901234567890             
REPLACE2  12345678901234567890             
Now ~1 TB of data follows...

:

Some Header
Replaced first!!!             
Replaced second!!!            
Now ~1 TB of data follows...
+1

All Articles