Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following operating system dependent system-calls: int unlink(char

ID: 3940063 • 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

#include<stdio.h> //For snprintf function
#include <sys/stat.h> //struct stat statbuf;
#include <string.h> //for strlen
#include <stdlib.h> //Malloc function
#include <dirent.h> //For DIR *d
int removeDirectory(char *directoryname)
{
DIR *d = opendir(directoryname);
size_t path_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. */
if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
{
continue;
}
len = path_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 = removeDirectory(buf);
}
else
{
//Delete file
r2 = unlink(buf);
}
}
//Release memory
free(buf);
}
r = r2;
}
//Closes
closedir(d);
}
if (!r)
{
//Removes directory
r = rmdir(directoryname);
}
return r;
}
int main()
{
char fname[50];
printf(" Enter the file name: ");
gets(fname);
removeDirectory(fname);
}

Output:

Enter the file name: E:checkdemo