dirent.h
dirent.h是一个头文件,它包含了在文件系统中进行目录操作的函数和数据结构的声明。
以下是一些dirent.h头文件中常用的函数和数据结构:
- DIR结构体:表示一个目录流,用于操作目录。
- struct dirent结构体:表示一个目录项,包含文件名和文件类型等信息。
- opendir函数:打开一个目录流,并返回一个指向
DIR
结构体的指针。 - readdir函数:读取目录流中的下一个目录项,并返回一个指向
struct dirent
结构体的指针。 - closedir函数:关闭一个目录流。
利用dirent遍历目录并获取目录中的条目信息
代码示例如下,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>#define MAX_FILENAME_LENGTH 256void processFiles(const char* folderPath) {DIR* directory;struct dirent* entry;directory = opendir(folderPath);if (directory == NULL) {printf("Failed to open the folder.\n");return;}while ((entry = readdir(directory)) != NULL) {if (entry->d_type == DT_REG) {char filePath[MAX_FILENAME_LENGTH];snprintf(filePath, sizeof(filePath), "%s/%s", folderPath, entry->d_name);char* extension = strrchr(entry->d_name, '.');if (extension != NULL && strcmp(extension, ".jpg") == 0) {printf("File Path: %s\n", filePath);}}}closedir(directory);
}int main() {const char* dataFolder = "C:\\Users\\reconova\\Desktop\\data_folder";processFiles(dataFolder);return 0;
}
首先,打开指定路径的目录,并将目录流(DIR*类型)赋值给directory变量,
DIR* directory;
struct dirent* entry;
directory = opendir(folderPath);
接下来,遍历目录中的条目,并检查每个条目的类型是否为普通文件(regular file),
(entry = readdir(directory)) != NULL;
(entry->d_type == DT_REG);
随后,构建文件的绝对路径,
char filePath[MAX_FILENAME_LENGTH];// 使用snprintf()函数将文件的完整路径格式化为字符串,并将结果存储在filePath数组中。snprintf()函数类似于printf()函数,但它可以指定输出字符串的最大长度,以避免缓冲区溢出。它接受多个参数,其中包括格式化字符串和要格式化的值
snprintf(filePath, sizeof(filePath), "%s/%s", folderPath, entry->d_name);
最后,获取文件名的后缀,并判断是否为需要的文件,
// strrchr用于在一个字符串中查找指定字符的最后一次出现的位置,并返回该位置的指针
char* extension = strrchr(entry->d_name, '.');// strcmp用于比较两个字符串的内容是否相同
extension != NULL && strcmp(extension, ".jpg") == 0;