bool FileInfoUtils_FillFileInfoWithNewestFilesInDir()

in src/diagnostics_component/utils/file_info_utils/src/file_info_utils.c [98:185]


bool FileInfoUtils_FillFileInfoWithNewestFilesInDir(FileInfo* logFiles, size_t logFileSize, const char* directoryPath)
{
    bool succeeded = false;

    if (logFiles == NULL || logFileSize == 0 || directoryPath == NULL)
    {
        return false;
    }

    memset(logFiles, 0, sizeof(FileInfo) * logFileSize);

    unsigned int totalFilesRead = 0;
    DIR* dp = ADUCPAL_opendir(directoryPath);

    if (dp == NULL)
    {
        goto done;
    }

    // Walk through each file and find each top level file
    do
    {
        struct dirent* entry = ADUCPAL_readdir(dp); //Note: No need to free according to man readdir is static
        struct stat statbuf;

        STRING_HANDLE filePath = STRING_new();

        if (filePath == NULL)
        {
            goto done;
        }

        if (entry == NULL)
        {
            break;
        }

        if (STRING_sprintf(filePath, "%s/%s", directoryPath, entry->d_name) != 0)
        {
            continue;
        }

        if (stat(STRING_c_str(filePath), &statbuf) == -1)
        {
            STRING_delete(filePath);
            continue;
        }

        // Note: Only care about the first level files that are not symbolic
        if (S_ISDIR(statbuf.st_mode) || S_ISLNK(statbuf.st_mode) || statbuf.st_size == 0)
        {
            STRING_delete(filePath);
            continue;
        }

        FileInfoUtils_InsertFileInfoIntoArray(logFiles, logFileSize, entry->d_name, statbuf.st_size, statbuf.st_mtime);

        STRING_delete(filePath);
        ++totalFilesRead;

    } while (totalFilesRead < MAX_FILES_TO_SCAN);

    if (logFiles[0].fileName == NULL)
    {
        goto done;
    }

    succeeded = true;

done:

    if (!succeeded)
    {
        // Free all the file names, if allocated.
        for (size_t i = 0; i < logFileSize; ++i)
        {
            free(logFiles[i].fileName);
            memset(&logFiles[i], 0, sizeof(FileInfo));
        }
    }

    if (dp != NULL)
    {
        ADUCPAL_closedir(dp);
    }

    return succeeded;
}