在文件中查找特定单词并删除其行

Find a specific word inside file and delete its line

如标题所示,我试图在文件中找到一个特定的单词,然后删除包含它的行,但我在这里所做的会破坏文件的内容:

cin>>ID; //id of the line we want to delete
ifstream read;
read.open("infos.txt"); 
ofstream write; 
write.open("infos.txt");
while (read >> name >> surname >> id) {
    if (ID != id) {
        write << name << " " << surname << " " << id << endl; 
    }
    else write << " ";
    }
    read.close();
    write.close();

您的两个文件同名。调用 basic_ofstream::open 会破坏文件的内容(如果它已经存在)。在您的情况下,您在执行任何操作之前销毁了输入文件中的数据。使用不同的名称,稍后重命名。我假设输入行以“\n”结尾,因此我们可以使用 getline()。然后我们需要判断单词是否存在于行中并且存在 this function。 std::string:npos 如果行不包含单词则返回。

#include <cstdio> // include for std::rename
#include <fstream>
#include <string>

void removeID() {
    std::string ID;
    cin >> ID; //id of the line we want to delete
    ifstream read("infos.txt");
    ofstream write("tmp.txt"); 
    if (read.is_open()) {
       std::string line;
       while (getline(read, line)) {
          if (line.find(ID) != std::string::npos)
             write << line;
       }
    } else {
       std::cerr << "Error: coudn't open file\n";
       /* additional handle */
    }

    read.close();
    write.close();
    std::remove("infos.txt");
    std::rename("tmp.txt", "infos.txt");
}