如何在C++中实现CSV文件24小时后自动删除指定行
实现CSV条目按24小时有效期清理
要清理CSV中超过24小时的条目,核心思路是读取原文件所有条目,筛选出未过期的记录,再覆盖写入原文件。以下是具体实现方案:
关键说明
- 原添加代码的时间格式问题:
ctime()返回的字符串自带换行符(如"Wed Jun 12 15:30:00 2024\n"),会导致读取时每行格式混乱,建议先优化添加逻辑,用可控的时间格式化方式。 - 时间判断逻辑:将CSV中的时间字符串转为
time_t类型,计算与当前时间的差值,若超过86400秒(24小时)则丢弃该条目。
完整实现代码
优化后的添加条目代码(可选,解决时间格式问题)
#include <iostream> #include <fstream> #include <chrono> #include <iomanip> using namespace std; int main() { string name; fstream myfile; myfile.open("Data.csv", ios::out | ios::app); if (!myfile.is_open()) { cerr << "无法打开文件!" << endl; return 1; } cout << "Enter the name:"; cin >> name; // 获取当前时间并格式化为无换行的标准字符串 auto now = chrono::system_clock::now(); time_t now_time = chrono::system_clock::to_time_t(now); tm local_tm = *localtime(&now_time); myfile << name << ";" << put_time(&local_tm, "%Y-%m-%d %H:%M:%S") << endl; myfile.close(); return 0; }
清理过期条目的核心代码
#include <iostream> #include <fstream> #include <vector> #include <string> #include <chrono> #include <ctime> #include <sstream> using namespace std; // 按分号分割字符串 vector<string> split(const string &s, char delimiter) { vector<string> tokens; string token; istringstream tokenStream(s); while (getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } // 将标准时间字符串转为time_t类型 time_t str_to_time(const string &time_str) { tm tm_time = {}; istringstream ss(time_str); ss >> get_time(&tm_time, "%Y-%m-%d %H:%M:%S"); return mktime(&tm_time); } int main() { const string csv_path = "Data.csv"; const int SECONDS_IN_DAY = 86400; vector<string> valid_entries; fstream infile(csv_path); if (!infile.is_open()) { cerr << "无法读取CSV文件!" << endl; return 1; } // 遍历每一行,筛选未过期条目 string line; while (getline(infile, line)) { if (line.empty()) continue; vector<string> fields = split(line, ';'); if (fields.size() != 2) continue; // 跳过格式错误的行 string time_str = fields[1]; time_t entry_time = str_to_time(time_str); if (entry_time == -1) continue; // 时间解析失败则跳过 // 计算当前时间与条目时间的差值 time_t now = chrono::system_clock::to_time_t(chrono::system_clock::now()); double diff = difftime(now, entry_time); if (diff <= SECONDS_IN_DAY) { valid_entries.push_back(line); // 保留未过期记录 } } infile.close(); // 将有效条目覆盖写入原文件 fstream outfile(csv_path, ios::out | ios::trunc); if (!outfile.is_open()) { cerr << "无法写入CSV文件!" << endl; return 1; } for (const string &entry : valid_entries) { outfile << entry << endl; } outfile.close(); cout << "过期条目清理完成,剩余" << valid_entries.size() << "条有效记录" << endl; return 0; }
额外注意事项
- 文件安全:如果担心原文件损坏,可以先将有效条目写入临时文件,确认写入成功后再替换原文件。
- 兼容原时间格式:若坚持使用
ctime()的输出格式,需将str_to_time的格式字符串改为"%a %b %d %H:%M:%S %Y",同时读取时要处理字符串末尾的换行符。 - 时区适配:代码使用本地时区(
localtime),若需UTC时间,可替换为gmtime。
内容的提问来源于stack exchange,提问作者M.S.Vishnu Kumar
相关产品推荐
相关产品推荐

