Solution


// search and replace a word in a text file
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>

void replaceInString(std::string& s, std::string needle, std::string replace) {
  int m = needle.length();
  int n = s.length();
  for(int i = 0; i < n; i++) {
    if (s.substr(i, m) == needle) {
      s.replace(i, m, replace, 0, replace.length());
    }
  }
}

int main(int argc, char** argv) {
  using namespace std;
  if (argc < 4) {
    cout << "need a filename, a word and its replacement on cmd line" << endl;
    return 1;
  }
  ifstream ifs(argv[1]);
  if (!ifs) {
    cout << "cannot open file " << argv[1] << endl;
    return 2;
  }
  string s;
  char c;
  while(!ifs.eof()) {
    ifs.get(c);
    if (c == ' ' || c == '\n') {
      cout << c;
    } else {
      ifs.putback(c);
    }
    ifs >> s;
    if (ifs.eof()) {
      break;
    }
    if (s == argv[2]) {
      cout << argv[3];
    } else {
      replaceInString(s, argv[2], argv[3]);
      cout << s;
    }
  }
  cout << endl;
  ifs.close();
  return 0;
}



Leo Liberti 2008-01-12