-
Notifications
You must be signed in to change notification settings - Fork 0
/
substr_remover.c
56 lines (46 loc) · 1.11 KB
/
substr_remover.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
int remover(char *pathname, char *sub){
int instances = 0;
DIR *mdir;
struct dirent *direntbuf;
struct stat statbuf;
if((mdir = opendir(pathname)) == NULL){
perror(pathname);
exit(1);
}
chdir(pathname);
while((direntbuf = readdir(mdir)) != NULL){
stat(direntbuf->d_name, &statbuf);
if(S_ISDIR(statbuf.st_mode)) {
if((strcmp(direntbuf->d_name, ".") != 0) && (strcmp(direntbuf->d_name, "..") != 0)){
instances += remover(direntbuf->d_name, sub);
chdir("..");
}
} else {
// Remove all files which names contain the selected substring
if(strstr(direntbuf->d_name, sub) != NULL){
instances++;
remove(direntbuf->d_name);
}
}
}
return instances;
}
int main(int argc, char **argv){
struct stat statbuf;
if(argc != 3){
printf("Usage: %s <dir> substring_file_to_remove\n", argv[0]);
exit(1);
}
stat(argv[1], &statbuf);
if (S_ISDIR(statbuf.st_mode)) {
printf("%d instances removed\n", remover(argv[1], argv[2]));
}
return 0;
}