Linux文件目录操作实战

发布于:2025-05-01 ⋅ 阅读:(31) ⋅ 点赞:(0)


本篇文章主要带大家实现两个功能:

1.统计目录内存占用率

2.统计当前目录文件数量及进行文件先后顺序的排序

下面是在 Linux 下使用 C语言 实现的 main.c,实现两个功能:


✅ 功能要求拆解:

统计当前目录的内存使用率

  • 使用 statvfs() 获取当前目录所在挂载点的空间使用情况(总空间 / 可用空间)。

统计当前目录及子目录下的所有文件

  • 使用 nftw()(递归遍历目录);
  • 记录每个文件路径和其最后修改时间;
  • 最后按时间升序打印出来。

✅ 完整的 main.c

#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ftw.h>
#include <sys/statvfs.h>
#include <sys/stat.h>
#include <time.h>

#define MAX_FILES 10000

// 用于存储文件信息
typedef struct {
    char path[1024];
    time_t mtime;
} FileInfo;

FileInfo files[MAX_FILES];
int file_count = 0;

// nftw 回调函数,收集普通文件信息
int collect_file(const char* fpath, const struct stat* sb, int typeflag, struct FTW* ftwbuf) {
    if (typeflag == FTW_F && file_count < MAX_FILES) {
        strncpy(files[file_count].path, fpath, sizeof(files[file_count].path) - 1);
        files[file_count].mtime = sb->st_mtime;
        file_count++;
    }
    return 0;
}

// 比较函数:按修改时间升序排序
int compare_files(const void* a, const void* b) {
    return ((FileInfo*)a)->mtime - ((FileInfo*)b)->mtime;
}

// 功能一:打印当前目录所在挂载路径的使用率
void print_disk_usage() {
    struct statvfs fs;
    if (statvfs(".", &fs) != 0) {
        perror("statvfs failed");
        return;
    }

    unsigned long total = fs.f_blocks * fs.f_frsize;
    unsigned long free = fs.f_bfree * fs.f_frsize;
    unsigned long used = total - free;

    double usage = (double)used / total * 100.0;
    printf(">>> 当前目录所在挂载点磁盘使用率: %.2f%%\n", usage);
}

// 功能二:遍历当前目录及子目录,统计并按时间打印所有文件
void scan_and_print_files() {
    printf("\n>>> 扫描当前目录及子目录中的文件...\n");

    // 遍历目录
    if (nftw(".", collect_file, 20, FTW_PHYS) == -1) {
        perror("nftw failed");
        return;
    }

    // 按时间排序
    qsort(files, file_count, sizeof(FileInfo), compare_files);

    // 打印结果
    for (int i = 0; i < file_count; ++i) {
        char buf[64];
        struct tm* t = localtime(&files[i].mtime);
        strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", t);
        printf("[%s] %s\n", buf, files[i].path);
    }
}

int main() {
    print_disk_usage();
    scan_and_print_files();
    return 0;
}

✅ 编译方式

创建一个简单的 Makefile

all:
	gcc main.c -o file_stat -lnftw

或者命令行手动编译:

gcc main.c -o file_stat -lnftw

然后运行程序:

./file_stat

✅ 输出示例

>>> 当前目录所在挂载点磁盘使用率: 23.45%

>>> 扫描当前目录及子目录中的文件...
[2025-04-26 09:12:00] ./test.txt
[2025-04-26 09:14:32] ./src/demo.c
[2025-04-26 09:15:10] ./README.md

在这里插入图片描述

✅ 说明与扩展

  • statvfs():用于获取文件系统信息(磁盘容量和使用率);
  • nftw():递归遍历当前目录和所有子目录;
  • qsort():排序所有文件的修改时间;
  • 可以扩展打印文件大小、类型,或过滤某类文件(如 .c)。

网站公告

今日签到

点亮在社区的每一天
去签到