Listing 2: Same as Listing 1 but with return codes

/* ddir2.c:  Remove subdirectory tree */

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <string.h>
#include <sys/stat.h>
#include <dirent.h>
#include <dir.h>

/* Return codes */
#define BAD_DIR 1
#define DIR_OPEN_ERR 2
#define FILE_DEL_ERR 3
#define DIR_DEL_ERR 4

main(int argc, char **argv)
{
    char *old_path = getcwd(NULL,64);
    int rd(char *);

    while (--argc)
    {
        int code = rd(*++argv);
        switch(code)
        {
            case BAD_DIR:
                puts("Invalid directory");
                break;
            case DIR_OPEN_ERR:
                puts("Error opening directory");
                break;
            case FILE_DEL_ERR:
                puts("Error deleting file");
                break;
            case DIR_DEL_ERR:
                puts("Error deleting directory");
                break;
        }
    }

    chdir(old_path);
    return 0;
}

int rd(char* dir)
{
    int erase_dir(void);
    int code;

    if (chdir(dir))
        return BAD_DIR;
    system("del /q *.* > nul");

    code = erase_dir();
    if (code)
        return code;

    chdir("..");
    if (rmdir(dir))
        return DIR_DEL_ERR;
    return 0;
}

int erase_dir()
{
    DIR *dirp;
    struct dirent *entry;
    struct stat finfo;
    
    if ((dirp = opendir(".")) == NULL)
        return DIR_OPEN_ERR;

    while ((entry = readdir(dirp)) != NULL)
    {
        if (entry->d_name[0] == '.')
            continue;
        stat(entry->d_name,&finfo);

        if (finfo.st_mode & S_IFDIR)
            rd(entry->d_name);
        else
        {
            chmod(entry->d_name,S_IWRITE);
            if (unlink(entry->d_name))
            {
                closedir(dirp);
                return FILE_DEL_ERR;
            }
        }
    }
    closedir(dirp);
    return 0;
}
//End of File