Consider the following operating system dependent systemcall
Solution
#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:\\check\\demo

