Consider the following operating system dependent system-calls: int unlink(char
ID: 3940081 • Letter: C
Question
Consider the following operating system dependent system-calls: int unlink(char *filename); int rmdir(char *directoryname); The unlink system-call may be used to remove a file from its parent directory, and the rmdir system-call may be used to remove a directory from its parent directory provided that directoryname itself contains no other files or directories. Assume that both system-calls return 0 on success, and 1 on failure. Using the unlink and rmdir system-calls, write a C99 function named removeDirectory that removes the indicated (potentially non-empty) directory and all of its contents. Your function should have the following prototype: int removeDirectory(char *directoryname); You should assume directoryname contains only files and directories. Your function should attempt to remove as many files and sub-directories as possible, returning 0 on complete success and non-zero otherwise. If directoryname could not be opened as a directory, your function should return -1.Explanation / Answer
Hi,
you can use the below program for the assignment here it goes :
the standard library dirent.h is for DIR file type and operations that we will perform on that
#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<string.h>
#include<sys/stat.h>
int removeDirectory(const char *directoryname)
{
/* Here we will open a directory and we will read all contents of a directory using readdir*/
DIR *d = opendir(directoryname);
size_t directoryname_len = strlen(directoryname);
int r = -1;
if (d)
{
struct dirent *p;
r = 0;
while (!r && (p=readdir(d)))
{
int r2 = -1;
char *buf;
size_t len;
/* Skip the names "." and ".." as we don't want to recurse on them. And we will recurse if the current name is directory .if the d_name is a file we will unlink it as given in the question */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
{
continue;
}
len = directoryname_len + strlen(p->d_name) + 2;
buf = (char*) malloc (len);
if (buf)
{
struct stat statbuf;
snprintf(buf, len, "%s/%s", directoryname, p->d_name);
if (!stat(buf, &statbuf))
{
if (S_ISDIR(statbuf.st_mode))
{
r2 = rmdir(buf);
}
else
{
r2 = unlink(buf);
}
}
free(buf);
}
r = r2;
}
closedir(d);
}
if (!r)
{
r = rmdir(directoryname);
}
return r;
}
int main(){
printf("%d",removeDirectory("userdirectorypath"));
}
you can use the main method to call the function removeDirecotry and pass the destinated path
thank you if have any further problem regarding code please comment below