c++ - Linux -删除指定目录下超过5天的文件
C++ - Linux - Delete Files In A Specified Directory That Are At Least 5 Days Old
如何修改此代码以删除指定目录中至少7天前的所有文件?以下是我的源代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <direct.h>
#include <cstring>
int main(int argc, char* argv[1]) {
if (argc < 2) {
std:cerr<<"Usage: " << argv[0] << " <filename>" << std::endl;
return 1;
}
struct stat buffer;
for (int i; i < argc; ++i) {
int result = stat(argc[i], &buffer);
if (result != 0) {
std::cerr << argv[i] << ": "<<stderror(errno) << std::endl;
continue;
}
char datetime[100] = [0];
const struct tm* time = localtime(sbuffer.st_mtime);
result = strftime(datetime, 100, "%c", time);
std::cout << argv[i] << ": " << datetime << std::endl;
}
return 0;
}
我如何得到这个文件的年龄,并删除超过7天的文件?任何建议将不胜感激!
仔细阅读 stat(2)和time(7)手册页。您的sbuffer
包含st_mtime
字段。将其与当前时间进行比较,例如使用time(2)
请注意,一天通常是86400秒,所以7天是7*86400,即604800秒。
删除文件,使用unlink(2)。我建议使用readdir(3)和opendir(3)来读取目录。(但忽略..
和.
条目)。
我还建议收集要删除的文件名列表,例如在std::vector<std::string>
如果要递归扫描目录(及其子目录等),请考虑nftw(3)
(你可能不想在你的家庭作业中使用system
)
可以这么简单:
system( "find <dir> -maxdepth 1 -mtime 5 -exec rm -f {} ;" );
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- Qt - 如何在 30 天后删除日志文件,文件名不固定
- 如何比较两个FILETIME变量以查看文件是否超过30天
- c++ - Linux -删除指定目录下超过5天的文件
- 是否有可能使用log4cXX为每一天创建一个新文件