代码详细注释:递归查找指定目录及其子目录中的所有BMP位图文件,并通过双重验证确保找到的文件确实是合法的BMP文件。以下是详细的功能说明:DIY机器人工房
#include <stdio.h> // 标准输入输出函数
#include <stdlib.h> // 标准库函数
#include <string.h> // 字符串处理函数
#include <dirent.h> // 目录操作函数
#include <sys/stat.h> // 文件状态函数
#include <stdbool.h> // 布尔类型支持
#include <limits.h> // 定义PATH_MAX等常量// 函数声明:检查文件扩展名是否为.bmp或.BMP
bool is_bmp_extension(const char *filename) {// 查找文件名中最后一个点号的位置const char *dot = strrchr(filename, '.');// 如果没有点号或点号在开头,返回falseif (!dot || dot == filename) return false;// 比较扩展名(不区分大小写),如果是.bmp返回truereturn (strcasecmp(dot, ".bmp") == 0);
}// 函数声明:检查文件头是否为"BM"
bool is_bmp_file(const char *filename) {// 以二进制模式打开文件FILE *file = fopen(filename, "rb");if (!file) return false; // 如果打开失败,返回falsechar header[2]; // 用于存储文件头的缓冲区// 读取文件的前2个字节size_t bytes_read = fread(header, 1, 2, file);fclose(file); // 关闭文件// 检查是否成功读取2个字节,且内容为'B'和'M'return (bytes_read == 2) && (header[0] == 'B') && (header[1] == 'M');
}// 函数声明:递归查找目录中的BMP文件
void find_bmp_files(const char *dir_path) {// 打开目录DIR *dir = opendir(dir_path);if (!dir) {perror("无法打开目录"); // 输出错误信息return;}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);struct stat statbuf; // 文件状态结构体// 获取文件状态信息if (stat(full_path, &statbuf) == -1) {perror("无法获取文件状态"); // 输出错误信息continue;}// 检查文件类型if (S_ISDIR(statbuf.st_mode)) {// 如果是目录,递归调用find_bmp_filesfind_bmp_files(full_path);} else if (S_ISREG(statbuf.st_mode)) {// 如果是普通文件,检查是否为BMP文件if (is_bmp_extension(entry->d_name) && is_bmp_file(full_path)) {printf("找到BMP文件: %s\n", full_path); // 输出找到的BMP文件路径}}}closedir(dir); // 关闭目录
}// 主函数
int main() {const char *my_directory = "/home/amai/play/bmp"; // 在这里修改为你的目录printf("正在搜索目录 %s 中的BMP文件...\n", my_directory);find_bmp_files(my_directory);return 0;
}
核心功能
-
递归目录扫描
-
从指定目录开始,遍历所有子目录
-
使用
opendir()
和readdir()
实现目录遍历 -
自动跳过
.
(当前目录)和..
(上级目录)
-
-
双重验证机制
-
扩展名验证:检查文件是否以
.bmp
或.BMP
结尾(不区分大小写) -
文件头验证:读取文件前2字节,确认是否为
BM
(标准BMP文件头标识)
-
-
路径处理
-
自动构建完整文件路径(父目录路径 + 文件名)
-
支持Linux路径格式(如
/home/user/images
)
-
关键函数说明
函数 | 功能 |
---|---|
is_bmp_extension() | 检查文件扩展名是否为.bmp (不区分大小写) |
is_bmp_file() | 验证文件头是否为BM (二进制模式读取) |
find_bmp_files() | 递归扫描目录,调用上述函数验证文件 |
main() | 设置搜索路径并启动扫描 |
使用方式
-
编译程序
bash
gcc find_bmp.c -o find_bmp
-
运行程序
-
搜索指定目录:
bash
./find_bmp /path/to/your/directory
-
搜索当前目录:
bash
./find_bmp .
-
-
输出示例
text
正在搜索目录 /home/user/images 中的BMP文件... 找到BMP文件: /home/user/images/photo1.bmp 找到BMP文件: /home/user/images/subdir/logo.BMP