C++读取文件并替换

标签 c++ readfile

我想读取一个有几行的文件,然后搜索特定的行,如果找到该行,我想用其他值替换该行,我该怎么做?

这是现在的情况:

#include <string>

using namespace std;

int main()
  {
  string line;

  ifstream myfile( "file.txt" );

  if (myfile) 

    {
    while (getline( myfile, line ))  
      {
      if (line == "my_match")
        {
        //cout << "found";
        ... here i would like to replace "my_match" with some other value
        }
      }
    myfile.close();
    }
  else cout << "error";

  return 0;
  }

最佳答案

我同意 Paul 的观点——Perl 很好:

  #!/usr/bin/perl -i.bak

  while (<>) {
     if (/^my_match$/) {
        print "replaced_line\n";
     } else {
        print "$_";
     }
  }

-i.bak 将自动替换您正在阅读的文件,并创建一个带有 .bak 扩展名的备份。

sed更好:

sed -i 's/^my_match$/replace_text/' file.txt

但是,在 C 中,为什么不将您的行写入标准输出,而不是重写文件。然后使用文件指令/bash 写入新文件?

如果您必须在 C++ 中执行此操作,读入内存然后写出是一种选择(假设您的文件永远不会太大):

  #include <string>
  #include <iostream>
  #include <fstream>
  #include <vector>

  using namespace std;

  int main()
  {
    string line;
    vector<string> buffer;

    ifstream in( "file.txt" );
    while (getline(in, line)) {
        buffer.push_back( (line == "my_match") ? "REPLACED" : line );
     }
     in.close();

     ofstream out("file.txt");
     for (vector<string>::iterator it = buffer.begin(); it!=buffer.end(); it++) {
        out << *it << endl;
     }

    return 0;
  }

如果您的文件可能太大,您需要写入一个临时文件,然后删除原始文件并重命名临时文件。

关于C++读取文件并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8861560/

相关文章:

c++ - 类/结构中的内联语句

c++ - 我们可以控制 vector 数组(c++)中元素的内存分配吗?

C++ GUI 窗口绘制了代码不应该绘制的形状

c++ - 如何连接到 "wss"[IBM Watson] 上的特定端点

java - 用java读取文本文件(带制表符)

c++ - 什么时候调用 stringbuf::flush?

C++ 显示文本文件... ("Echo"文本文件)

C 文本文件到结构体、数组,然后输出

python - 同时逐行读取两个文本文件

parsing - .next()方法在 `std::string::String`中找不到