反复阅读和写作之间的交替

时间:2016-03-20 02:37:00

标签: c++ fstream

我的目标是逐行读取文件,检查该行是否包含某个数字,如果是,则重写该行。然后继续阅读该文件。 我已经成功地为一行做了这个,但我无法弄清楚如何继续阅读文件的其余部分。 这是我如何替换一行(每行是已知的固定大小):

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;
  }
}

如何切换回读取并继续getline循环?

1 个答案:

答案 0 :(得分:1)

我有同样的问题,TB级文件,我想修改文件开头的一些标题信息。 显然,当最初为任何新内容创建文件时,必须留出足够的空间,因为没有办法增加文件大小(除了附加到它)并且新行必须具有与原始文件完全相同的行长度

以下是我的代码的简化:

#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...