-
Notifications
You must be signed in to change notification settings - Fork 0
/
Experiment 4
205 lines (77 loc) · 2.45 KB
/
Experiment 4
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
Q1 Create a C program that prompts the user to enter a directory name and uses the mkdir system call to create the directory.
Ans.1
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
int main() {
char dirname[100];
// Prompt user to enter directory name
printf("Enter directory name: ");
scanf("%s", dirname);
// Create directory using mkdir system call
if (mkdir(dirname, 0777) == -1) {
perror("Error creating directory");
exit(EXIT_FAILURE);
}
printf("Directory '%s' created successfully.\n", dirname);
return 0;
}
Q2)Write a program that opens the current directory using opendir and reads its contents using readdir, then displays the list of directory entrics.
Ans.2
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
// Open current directory
dir = opendir(".");
if (dir == NULL) {
perror("Error opening directory");
exit(EXIT_FAILURE);
}
// Read directory entries and display them
printf("Contents of current directory:\n");
while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
// Close directory
closedir(dir);
return 0;
}
Q3) Create a C program to delete a directory specified by the user using the rmdir system call.
Ans.3
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
char dirname[100];
// Prompt user to enter directory name
printf("Enter directory name to delete: ");
scanf("%s", dirname);
// Delete directory using rmdir system call
if (rmdir(dirname) == -1) {
perror("Error deleting directory");
exit(EXIT_FAILURE);
}
printf("Directory '%s' deleted successfully.\n", dirname);
return 0;
}
q4)Write a program that uses the getcud system call to retrieve the current working directory and displays it to the user.
Ans. 4
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_PATH_LEN 4096
int main() {
char cwd[MAX_PATH_LEN];
// Get current working directory using getcwd system call
if (getcwd(cwd, sizeof(cwd)) == NULL) {
perror("Error getting current working directory");
exit(EXIT_FAILURE);
}
// Print current working directory
printf("Current working directory: %s\n", cwd);
return 0;
}