在 CentOS 系统中,使用 readdir 函数进行文件校验通常涉及以下几个步骤:
opendir 函数打开一个目录。readdir 函数读取目录中的每个条目。closedir 函数关闭目录。以下是一个简单的示例代码,展示了如何使用 readdir 函数进行文件校验:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
void check_file(const char *path) {
struct stat file_stat;
if (stat(path, &file_stat) == 0) {
// 获取文件的修改时间
char time_buf[20];
strftime(time_buf, sizeof(time_buf), "%Y-%m-%d %H:%M:%S", localtime(&file_stat.st_mtime));
printf("File: %s, Modified Time: %s\n", path, time_buf);
// 获取文件大小
printf("File Size: %ld bytes\n", file_stat.st_size);
// 获取文件权限
printf("File Permissions: %o\n", file_stat.st_mode & 0777);
} else {
perror("stat");
}
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
const char *dir_path = argv[1];
DIR *dir = opendir(dir_path);
if (dir == NULL) {
perror("opendir");
return EXIT_FAILURE;
}
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// 跳过当前目录和上级目录
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
continue;
}
// 构建完整路径
char full_path[PATH_MAX];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, entry->d_name);
// 校验文件
check_file(full_path);
}
closedir(dir);
return EXIT_SUCCESS;
}
opendir 函数打开指定目录。readdir 函数读取目录中的每个条目。stat 函数获取文件的详细信息,并进行校验。closedir 函数关闭目录。gcc -o check_files check_files.c
./check_files /path/to/directory
这个示例代码会遍历指定目录中的所有文件和子目录,并输出每个文件的修改时间、大小和权限。你可以根据需要扩展校验逻辑,例如检查文件类型、文件名模式等。