首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 刪除文字檔最後一行

     編輯:關於C++

方法

  1. 逐行讀取檔案內容至 std::vector<std::string>。
  2. 寫回時略過最後一個元素(end()-1)。

程式碼示範

/* main.cpp
 * Created on: 2014.06.08
 * Author: Spike
 */
#include <windows.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

int main() {
    vector<string> tmp_files;
    ifstream infile("w.txt");
    if (!infile) { cout << "fail!" << endl; return 0; }
    string lineContent;
    while (getline(infile, lineContent, '\n')) {
        tmp_files.push_back(lineContent + "\n");
    }
    infile.close();

    ofstream outfile("w2.txt", ios::out);
    copy(tmp_files.begin(), tmp_files.end() - 1,
         ostream_iterator<string>(outfile));
    cout << "ok!" << endl;
    outfile.close();
    return 0;
}

範例

原始檔 (w.txt):
Female
Sister
Girl
Woman
Old Woman

輸出檔 (w2.txt):
Female
Sister
Girl
Woman

替代方案

  • 若檔案極大,可雙向迭代器從尾端讀取尋找最後一個換行符,截斷檔案(std::fstream::truncate),避免全量載入記憶體。
  • 使用 std::filesystem::copy_file 配合流處理管線(C++17)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved