C++ 读取和修改 txt 文件中的行

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

本文关键字:文件 txt 读取 修改 C++      更新时间:2023-10-16

我在搜索单词第一次出现的位置时遇到了一些困难。该软件必须搜索确定的txt文件中指定的单词。所以我使用 fstream 库打开并毕竟写了一些东西。但是我不知道我将如何使软件获得该单词的确切位置。我得到的只是这个:

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

有什么建议吗?

不要尝试更改文件中的字节。 创建一个新文件,复制这些行,直到找到要替换的行,输出新行,然后输出其余行。 因为除非您将一个字符串替换为另一个具有完全相同字符数的字符串,否则您将覆盖文件中的下一行 - 并且没有好方法可以避免这种情况。

如果需要,可以

删除原始文件,并将新文件重命名为该名称。