简体   繁体   中英

C++ Read and modify a line in a txt file

I'm facing some difficulties with the searching of the position of the first occurrence of a word. The software have to search into a determined txt file a specified word. So I've used the fstream lib to open and after all write something. But I have no clue how I will make the software to get the exactly position of the that word. All I got is this:

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

int main() {
  fstream myfile; // fstream to read and write the myfile
  string  cText = "\n--something--!\n"; // what it will write
  string  line; // will assign the getline() value;
  unsigned int pos = 0; //will be assigned to "seekp" - where it will start to write

  myfile.open( "example.html", ios::binary | ios::in | ios::out );

  if( !myfile ) {
    cout << "File does not exist!" << endl;
    cin.get();
    return false;
  }

  do {
    size_t found = line.find("<head>");
    cout << string::npos << endl;
    if (found != string::npos) {
        cout << line << endl;

    }
  }while( getline(myfile, line));

  myfile.seekp( pos+1, ios::beg );
  //myfile.write( cText, strlen( cText ) ); //write cText
  myfile.close();
  cin.get();
  return 0;
}

Any suggestions?

Don't try to change the bytes in your file. Make a new file, copy the lines over until you find the one you want to replace, output your new line, then output the rest of your lines. Because unless you're replacing one string, with another string with exactly the same number of characters, you're going to be overriding the next line in your file - and there's no good way to avoid that.

If you want to, you can then delete the original file, and rename your new file to that name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM