【问题标题】:c++ how to remove/replace the last line of a file?c++ 如何删除/替换文件的最后一行?
【发布时间】:2023-03-05 05:56:01
【问题描述】:

如何在 C++ 中删除/替换文件的最后一行?我看了这些问题: Deleting specific line from fileRead and remove first (or last) line from txt file without copying 。我想过迭代到文件的末尾,然后替换最后一行,但我不知道该怎么做。

【问题讨论】:

    标签: c++ file stream


    【解决方案1】:

    查找文件内容中最后一次出现“\n”的位置。如果文件以'\n'结尾,即在最后一个'\n'之后没有更多数据,则查找上一个'\n'出现的位置。使用resize_file在找到的位置截断文件或只替换找到位置之后的内容。

    【讨论】:

      【解决方案2】:
      #include <fstream>
      #include <string>
      using namespace std;
      
      int main() {
          ifstream fin("input.txt");
          ofstream fout("output.txt");
      
          
          while (!fin.eof()) {
              string buffer;
              getline(fin, buffer);
              
              if (fin.eof()) {
                  fout << "text to replace last line";
              } else {
                  fout << buffer << '\n';
              }
          }
      
          fin.close();
          fout.close();
      }
      

      您还可以读取和存储所有输入文件,修改然后写入:

      #include <fstream>
      #include <vector>
      #include <string>
      using namespace std;
      
      int main() {
          // read
          ifstream fin("input.txt");
          vector<string> lines;
          
          while (!fin.eof()) {
              string buffer;
              getline(fin, buffer);
              lines.push_back(buffer + '\n');
          }
          fin.close();
      
          // modify
          lines[lines.size() - 1] = "text to replace last line";
      
          // write
          ofstream fout("output.txt");
          for (string line: lines) { // c++11 syntax
              fout << line;
          }
          fout.close();
      }
      

      【讨论】:

      • fin.eof() 在循环体中始终为 false。
      • @S.M.我刚刚阅读了您提供的链接,如何在不使用 eof 的情况下转到文件末尾?
      • 链接的答案包含代码中错误的信息,但问题标题可能会混淆。我删除了链接。
      • @Meowster 不。如果(getline(fin, buffer)) 为真,则fin.eof() 为假。
      • wandbox.org/permlink/LEdegHHks7pefPoj true 永远不会输出。
      猜你喜欢
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2013-09-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多