1、查看磁盘剩余容量
int get_free_memory(const char* path, uint64_t* total, uint64_t* free)
{
struct statfs diskInfo;
int ret = statfs(path, &diskInfo);
if (ret < 0)
{
printf("statfs = -1\r\n");
return -1;
}
unsigned long long blocksize = diskInfo.f_bsize;// 每个block里面包含的字节数
unsigned long long totalsize = blocksize * diskInfo.f_blocks;//总的字节数
*total = totalsize;
char totalsize_GB[10] = {
0 };
//printf("TOTAL_SIZE == %llu KB %llu MB %llu GB\n", totalsize >> 10, totalsize >> 20, totalsize >> 30); // 分别换成KB,MB,GB为单位
sprintf(totalsize_GB, "%.2f", (float)(totalsize >> 20) / 1024);
//printf("totalsize_GB=%s\n", totalsize_GB);
unsigned long long freesize = blocksize * diskInfo.f_bfree; //再计算下剩余的空间大小
*free = freesize;
//printf("DISK_FREE == %llu KB %llu MB %llu GB\n", freesize >> 10, freesize >> 20, freesize >> 30);
unsigned long long usedsize = blocksize * (diskInfo.f_blocks - diskInfo.f_bfree);
char usedsize_GB[10] = {
0 };
sprintf(usedsize_GB, "%.2f", (float)(usedsize >> 20) / 1024);
//printf("usedsize_GB=%s\n", usedsize_GB);
return 0;
}
2、删除文件
void delete_directory(const char* path) {
DIR* dir = opendir(path);
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
// check if entry is a directory
if (entry->d_type == DT_DIR) {
// skip . and ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// delete subdirectory
char sub_path[1000];
snprintf(sub_path, sizeof(sub_path), "%s/%s", path, entry->d_name);
delete_directory(sub_path);
}
else {
// delete file
char file_path[1000];
snprintf(file_path, sizeof(file_path), "%s/%s", path, entry->d_name);
remove(file_path);
}
}
closedir(dir);
rmdir(path);
}
3、删除给定时间前的文件
void deleteOldFiles(const char* directoryPath, int daysThreshold) {
DIR* dir = opendir(directoryPath);
if (dir == NULL) {
printf("Failed to open directory: %s\n", directoryPath);
return;
}
struct dirent* entry;
struct stat fileStat;
char filePath[1024];
time_t currentTime = time(NULL);
time_t threshold = (daysThreshold * 24 * 60 * 60);
while ((entry = readdir(dir)) != NULL) {
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
continue;
snprintf(filePath, sizeof(filePath), "%s/%s", directoryPath, entry->d_name);
if (stat(filePath, &fileStat) == -1) {
printf("Failed to get file stats: %s\n", filePath);
continue;
}
if ( difftime(currentTime, fileStat.st_mtime) > threshold) {
delete_directory(filePath);
}
else
{
//printf("file: %s ,%d:%d,%f,threshold%ld\n", filePath, S_ISREG(fileStat.st_mode), S_ISDIR(fileStat.st_mode), difftime(currentTime, fileStat.st_mtime), threshold);
}
}
closedir(dir);
}