使用c++检查Linux系统硬盘空间,如果空间少于200m时删除最老的文件
时间: 2023-02-24 18:11:26 浏览: 273
使用C语言检查Linux系统硬盘空间,如果空间少于200MB,删除最早的文件可以使用下面的代码:
```
#include <sys/statvfs.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#define THRESHOLD 200*1024*1024 // 200MB in bytes
int main(int argc, char* argv[])
{
struct statvfs disk_stat;
if (statvfs("/", &disk_stat) != 0)
{
perror("statvfs");
return 1;
}
unsigned long long free_space = disk_stat.f_frsize * disk_stat.f_bfree;
if (free_space < THRESHOLD)
{
DIR *dir = opendir("/");
if (dir == NULL)
{
perror("opendir");
return 1;
}
struct dirent *entry = readdir(dir);
while (entry != NULL)
{
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
{
entry = readdir(dir);
continue;
}
char path[1024];
snprintf(path, sizeof(path), "/%s", entry->d_name);
struct stat file_stat;
if (lstat(path, &file_stat) != 0)
{
perror("lstat");
return 1;
}
if (S_ISREG(file_stat.st_mode))
{
time_t oldest_time = time(NULL);
char oldest_file[1024];
struct dirent *inner_entry = readdir(dir);
while (inner_entry != NULL)
{
char inner_path[1024];
snprintf(inner_path, sizeof(inner_path), "/%s", inner_entry->d_name);
struct stat inner_file_stat;
if (lstat(inner_path, &inner_file_stat) != 0)
{
perror("lstat");
return 1;
}
if (S_ISREG(inner_file_stat.st_mode) && inner_file_stat.st_mtime < oldest_time)
{
oldest_time = inner_file_stat.st_mtime;
strncpy(oldest_file, inner_path, sizeof(oldest_file));
}
inner_entry = readdir(dir);
}
if (remove(oldest_file) != 0)
{
perror("remove");
return 1;
}
if (statvfs("/", &
阅读全文