【问题标题】:Find a specific word inside file and delete its line [closed]在文件中查找特定单词并删除其行[关闭]
【发布时间】:2017-04-26 00:34:19
【问题描述】:

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

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

【问题讨论】:

标签: c++ file overwrite


【解决方案1】:

您的两个文件具有相同的名称。如果文件内容已经存在,则调用 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");
}

【讨论】:

  • 所以没有办法从同一个文件中删除?
  • 为什么需要它?您最终会得到与旧文件同名的更新文件
  • 这个方法也很好用,我在看到编辑之前问过
  • 很高兴我能帮上忙 ^_^。您应该将此问题标记为已回答
猜你喜欢
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 2013-08-05
  • 2020-01-28
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
相关资源
最近更新 更多