首先创建一个C文件,例如 myfind.c:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <fnmatch.h>
#include <time.h>
#include <pthread.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_THREAD 10
typedef struct find_args {
char path[PATH_MAX];
char *file_name;
int mtime;
int ctime;
bool print;
bool exec;
char *exec_cmd;
} find_args;
void *find(void *arg) {
find_args *fa = (find_args *) arg;
struct dirent *entry;
DIR *dp;
struct stat f_stat;
char new_path[PATH_MAX];
int exec_ret;
dp = opendir(fa->path);
if (dp == NULL) {
perror("opendir");
return NULL;
}
chdir(fa->path);
while((entry = readdir(dp)) != NULL) {
stat(entry->d_name, &f_stat);
if (fnmatch(fa->file_name, entry->d_name, 0) == 0) {
if ((time(NULL) - f_stat.st_mtime) / 86400 <= fa->mtime) {
if ((time(NULL) - f_stat.st_ctime) / 86400 <= fa->ctime) {
if (fa->print) {
printf("%s/%s\n", fa->path, entry->d_name);
}
if (fa->exec) {
exec_ret = system(fa->exec_cmd);
if (exec_ret < 0)
perror("system");
}
}
}
}
if (S_ISDIR(f_stat.st_mode) && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0 && strcmp(entry->d_name, ".git") != 0) {
find_args new_fa;
strcpy(new_fa.path, fa->path);
strcat(new_fa.path, "/");
strcat(new_fa.path, entry->d_name);
new_fa.file_name = fa->file_name;
new_fa.mtime = fa->mtime;
new_fa.ctime = fa->ctime;
new_fa.print = fa->print;
new_fa.exec = fa->exec;
new_fa.exec_cmd = fa->exec_cmd;
find((void *)&new_fa);
}
}
chdir("..");
closedir(dp);
return NULL;
}
int main(int argc, char *argv[]) {
find_args fa;
if (argc < 3) {
printf("Usage: %s <path> <filename> [-print] [-mtime days] [-ctime days] [-exec command]\n", argv[0]);
exit(EXIT_FAILURE);
}
strcpy(fa.path, argv[1]);
fa.file_name = argv[2];
fa.mtime = INT_MAX;
fa.ctime = INT_MAX;
fa.print = false;
fa.exec = false;
for (int i = 3; i < argc; i++) {
if (strcmp(argv[i], "-print") == 0) {
fa.print = true;
} else if (strcmp(argv[i], "-mtime") == 0) {
if (i + 1 < argc) {
fa.mtime = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-ctime") == 0) {
if (i + 1 < argc) {
fa.ctime = atoi(argv[++i]);
}
} else if (strcmp(argv[i], "-exec") == 0) {
if (i + 1 < argc) {
fa.exec = true;
fa.exec_cmd = argv[++i];
}
}
}
find((void *)&fa);
return 0;
}
编译这个程序:
gcc -o myfind myfind.c -lpthread
一些例子关于如何使用这个程序:
./myfind /etc *.conf -print
./myfind /usr/src -mtime 7 -print
./myfind /tmp -ctime 3 -print
./myfind /tmp "*.txt" -exec "rm {}"