celix_status_t celix_utils_deleteDirectory()

in libs/utils/src/celix_file_utils.c [152:207]


celix_status_t celix_utils_deleteDirectory(const char* path, const char** errorOut) {
    const char *dummyErrorOut = NULL;
    if (errorOut) {
        //reset errorOut
        *errorOut = NULL;
    } else {
        errorOut = &dummyErrorOut;
    }

    bool fileExists = celix_utils_fileExists(path);
    bool dirExists = celix_utils_directoryExists(path);
    if (!fileExists) {
        //done
        return CELIX_SUCCESS;
    } else if (!dirExists) {
        //found file not directory;
        *errorOut = CANNOT_DELETE_DIRECTORY_PATH_IS_FILE;
        return CELIX_FILE_IO_EXCEPTION;
    }

    //file exist and is directory
    celix_status_t status = CELIX_SUCCESS;
    char *paths[] = { (char*)path, NULL };
    FTS *fts = fts_open(paths, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, NULL);
    if (fts == NULL) {
        goto out;
    }
    FTSENT *ent = NULL;
    while ((ent = fts_read(fts)) != NULL) {
        switch (ent->fts_info) {
            case FTS_DP:
            case FTS_NSOK:
            case FTS_SL:
            case FTS_SLNONE:
                if (remove(ent->fts_accpath) != 0) {
                    goto out;
                }
                break;
            case FTS_DNR:
            case FTS_ERR:
                errno = ent->fts_errno;
                goto out;
            default:
                break;
        }
    }
out:
    if (errno != 0) {
        status = CELIX_ERROR_MAKE(CELIX_FACILITY_CERRNO,errno);
        *errorOut = strerror(errno);
    }
    if (fts != NULL) {
        fts_close(fts); // it may change errno
    }
    return status;
}