最近工作中需要实现一个模糊匹配的功能,这里记录一下实现方式:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#define HASH_SIZE 1000 // 哈希表大小,根据实际情况调整
typedef struct Node {
char filename[256]; // 文件名最大长度
char path[1024]; // 文件路径
struct Node *next;
} Node;
Node *hash_table[HASH_SIZE];
unsigned int hash(const char *str) {
unsigned int hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c;
}
return hash % HASH_SIZE;
}
void insert_to_hash(const char *filename, const char *path) {
unsigned int index = hash(filename);
Node *new_node = (Node *)malloc(sizeof(Node));
strcpy(new_node->filename, filename);
strcpy(new_node->path, path);
new_node->next = hash_table[index];
hash_table[index] = new_node;
}
void search_in_hash(const char *keyword) {
for (int i = 0; i < HASH_SIZE; i++) {
Node *current = hash_table[i];
while (current != NULL) {
if (strstr(current->filename, keyword) != NULL) {
printf("Matching file found: %s\n", current->path);
}
current = current->next;
}
}
}
void scan_audio_files(const char *path) {
DIR *dir;
struct dirent *entry;
if ((dir = opendir(path)) == NULL) {
perror("opendir");
exit(EXIT_FAILURE);
}
while ((entry = readdir(dir)) != NULL) {
char full_path[1024];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
if (entry->d_type == DT_REG) {
insert_to_hash(entry->d_name, full_path); // 将文件名和路径插入哈希表中
} else if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
scan_audio_files(full_path);
}
}
closedir(dir);
}
int main() {
const char *directory_to_scan = "/home/lx/linux_c/scan_file/scan_file"; // 替换为你要扫描的目录路径
scan_audio_files(directory_to_scan);
// 在这里实现用户输入关键字进行模糊匹配检索
char keyword[100];
printf("Enter keyword: ");
scanf("%s", keyword);
search_in_hash(keyword);
return 0;
}
输出如下: