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

时间:2016-12-10 18:33:59

标签: c++ file overwrite

正如标题所暗示的那样,我尝试了这一点,但似乎它不起作用

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();

1 个答案:

答案 0 :(得分:2)

您的两个文件都有相同的名称。调用basic_ofstream :: open会破坏文件的内容(如果已存在)。在您的情况下,您在执行任何操作之前都会在输入文件中销使用不同的名称,然后重命名。我假设输入中的行以“\ n”结束,因此我们可以使用getline()。然后我们需要判断单词是否存在于行中,并且存在this function。 std :: string:如果line不包含单词,则返回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");
}