首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 刪除 TXT 指定關鍵字行:讀取→過濾→重寫兩種策略

     編輯:程式設計疑難解答

需求:依學號 (`Sno`) 刪除學生資料檔中對應行。

策略一:小檔案全讀記憶體過濾 (簡單、適合 < 100MB)


#include 
#include 
#include 
#include 

struct Student { long long Sno; std::string Sname, Ssex; int Sage; std::string Sdept; };

void deleteBySno(const std::string& filename, long long targetSno) {
    std::vector students;
    // 1. 讀取
    std::ifstream in(filename);
    std::string line;
    while (std::getline(in, line)) {
        if (line.empty()) continue;
        std::istringstream iss(line);
        Student s;
        if (iss >> s.Sno >> s.Sname >> s.Ssex >> s.Sage >> s.Sdept)
            students.push_back(s);
    }
    in.close();

    // 2. 過濾
    auto it = std::remove_if(students.begin(), students.end(),
                             [targetSno](const Student& s){ return s.Sno == targetSno; });
    students.erase(it, students.end());

    // 3. 覆寫
    std::ofstream out(filename, std::ios::trunc);
    for (const auto& s : students)
        out << s.Sno << ' ' << s.Sname << ' ' << s.Ssex << ' ' << s.Sage << ' ' << s.Sdept << '\n';
}

策略二:大檔案臨時檔流式處理 (記憶體恆定)


#include 
#include 

void deleteBySnoLarge(const char* src, const char* tmp, long long targetSno) {
    FILE* fin = fopen(src, "r");
    FILE* fout = fopen(tmp, "w");
    char line[1024];
    long long sno;
    while (fgets(line, sizeof(line), fin)) {
        if (sscanf(line, "%lld", &sno) == 1 && sno == targetSno) continue; // 跳過
        fputs(line, fout);
    }
    fclose(fin); fclose(fout);
    remove(src);
    rename(tmp, src);
}

關鍵細節

  • **欄位分隔符一致**:讀寫皆用空白/Tab,避免 `Sname` 含空格導致解析錯位 → 建議用 CSV (逗號分隔 + 雙引號) 或固定寬度。
  • **原子性替換**:寫入暫存檔 → `rename` 覆蓋原檔,避免寫入中斷損壞原檔。
  • **編碼一致**:讀寫皆用 UTF-8 (或系統預設),含中文時注意 `std::locale` / `fopen` 模式。

進階:SQLite 替代純文字檔

若頻繁增刪改查,直接用 **SQLite** (`DELETE FROM student WHERE Sno=?`),獲得索引、事務、並發支援,代碼更簡潔健壯。

選對策略:小檔全讀記憶體最簡單,大檔臨時檔流式最省記憶體,長期專案建議遷移 SQLite。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved