fstream - replace line?

hello, my head has been spinning around a way to do this. the best way to describe it would be with psudo code so...

ReplaceLine (string file, string keyword, string str) {
open file "file"
search for first line containing keyword "keyword"
replace that entire line with string "str"
save file "file"

return 0
}

very undetailed but, deliberately so. for instance for efficiency would you read in the entire file or using while(!file.eof()) go through line by line.
presumably the line by line search. but the replacing part is what is making me stuck.

anyway, thanks alot
Dead.Rabit
Just read line by line. Take a look at the getline() string function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// echo's input to output, prepending the line number
#include <iostream>
#include <string>
using namespace std;

int main() {
  string line;
  int line_number = 1;
  while (cin) {
    getline( cin, line );
    cout << line_number++ << line << endl;
    }
  return EXIT_SUCCESS;
  }

Compile with:
g++ -o a a.cpp

Test with
a < a.cpp

Hope this helps.
Last edited on
Topic archived. No new replies allowed.