需求:依學號 (`Sno`) 刪除學生資料檔中對應行。
#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);
}
若頻繁增刪改查,直接用 **SQLite** (`DELETE FROM student WHERE Sno=?`),獲得索引、事務、並發支援,代碼更簡潔健壯。
選對策略:小檔全讀記憶體最簡單,大檔臨時檔流式最省記憶體,長期專案建議遷移 SQLite。