-
Notifications
You must be signed in to change notification settings - Fork 1
/
mkdir.c
92 lines (76 loc) · 1.86 KB
/
mkdir.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "myshell.h"
char* getParentPath(char* newDirPath);
int indexOfLast(char* str, char ch);
int makedir(char* options, char* newDirPath);
int simpleMkdir(char* pathName);
int main(int argc, char** argv){
char* options = argv[0];
char** paths = argv+1;
int numOfPaths = argc-1;
if(argc==0){
printf("Enter file name to perform action\n");
return -1;
}
for(int i=0;i<numOfPaths;i++){
makedir(options,paths[i]);
}
return 0;
}
int makedir(char* options, char* newDirPath){
char* cwd = getenv("PWD");
char* fileName = malloc(PATH_MAX);
//resolve relative path at start of pathName
if(fileName[0]!='/'){
sprintf(fileName,"%s/%s",cwd,newDirPath);
//printf("FileName changed to %s\n",fileName);
}else{
memcpy(fileName,newDirPath,strlen(newDirPath));
fileName[strlen(fileName)]=0;
}
//get parent path name
newDirPath = fileName;
char* parentOfDir = getParentPath(newDirPath);
//check if parent is valid
struct stat statBuf;
if(stat(parentOfDir,&statBuf)<0){
perror("invalid parent directory");
return -1;
}
if(S_ISDIR(statBuf.st_mode)){
simpleMkdir(newDirPath);
}
return 0;
}
int indexOfLast(char* str, char ch){
int i=0,index=-1;
//printf("indexOfLast: %s\n",str);
for(i = 0; i < strlen(str); i++)
{
if(str[i] == ch)
{
//printf("%d\t",i);
index = i;
}
}
return index;
}
int simpleMkdir(char* pathName){
//printf("simpleMkdir: %s\n",pathName);
if(mkdir(pathName,0777)<0){
perror("Unable to create directory");
return -1;
}else{
printf("Directory Created:%s\n",pathName);
return 0;
}
}
char* getParentPath(char* newDirPath){
char* parent = malloc(PATH_MAX);
if(newDirPath[strlen(newDirPath)-1]=='/')
newDirPath[strlen(newDirPath)-1] = 0;
int length = indexOfLast(newDirPath,'/');
//printf("indexOf :%d\n",length);
strncat(parent,newDirPath,length);
parent[strlen(parent)]=0;
return parent;
}