测试
#include <iostream>
#include <string>
#include <vector>
#include <filesystem>
#include <sys/stat.h>
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
#include <io.h>
std::vector<std::string> getTxtFilePaths(const std::string& folderPath) {
std::vector<std::string> txtFilePaths;
struct _finddata_t fileInfo;
std::string searchPath = folderPath + "\\*.txt";
long long handle;
if ((handle = _findfirst(searchPath.c_str(), &fileInfo)) == -1) {
std::cout << "没有找到匹配文件!" << std::endl;
return txtFilePaths;
}
do {
std::string filePath = folderPath + "\\" + fileInfo.name;
txtFilePaths.push_back(filePath);
} while (_findnext(handle, &fileInfo) == 0);
_findclose(handle);
return txtFilePaths;
}
// 删除超过 30 天的文件
void deleteOldTxtFiles(const std::string& directoryPath) {
std::vector<std::string> txtFiles = getTxtFilePaths(directoryPath);
time_t currentTime = time(nullptr);
for (const std::string& filePath : txtFiles) {
struct stat fileStat;
if (stat(filePath.c_str(), &fileStat) == 0) {
time_t fileCreationTime = fileStat.st_ctime;
double daysPassed = difftime(currentTime, fileCreationTime) / (60 * 60 * 24);
std::cout << "文件: " << filePath << " 创建时长:" << difftime(currentTime, fileCreationTime) << std::endl;
if (daysPassed > 30) {
if (remove(filePath.c_str()) == 0) {
std::cout << "文件 " << filePath << " 已删除,因其创建超过 30 天。" << std::endl;
}
else {
std::cerr << "无法删除文件 " << filePath << std::endl;
}
}
}
else {
std::cerr << "无法获取文件 " << filePath << " 的状态" << std::endl;
}
}
}
int main() {
std::string directoryPath = "test"; // 将此处替换为实际的文件夹路径
deleteOldTxtFiles(directoryPath);
return 0;
}

浙公网安备 33010602011771号