Is it possible to get list of files in directory using apache portable runtime?

StackOverflow https://stackoverflow.com/questions/19907411

  •  30-07-2022
  •  | 
  •  

Pregunta

I need to get list of files in directory using APR. How can I do it? I was looking for answer in documentation, but found nothing. Thanks!

¿Fue útil?

Solución

The function you want is apr_dir_open. I found the header files to be the best documentation for APR

http://apr.apache.org/docs/apr/1.4/group_apr_dir.html

Here is an example for reading "." and reporting errors if any were encountered

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <apr.h>
#include <apr_errno.h>
#include <apr_pools.h>
#include <apr_file_info.h>

static void apr_fatal(apr_status_t rv);

int main(void)
{
    apr_pool_t *pool;
    apr_status_t rv;

    // Initialize APR and pool
    apr_initialize();
    if ((rv = apr_pool_create(&pool, NULL)) != APR_SUCCESS) {
        apr_fatal(rv);
    }

    // Open the directory
    apr_dir_t *dir;
    if ((rv = apr_dir_open(&dir, ".", pool)) != APR_SUCCESS) {
        apr_fatal(rv);
    }

    // Read the directory
    apr_finfo_t finfo;
    apr_int32_t wanted = APR_FINFO_NAME | APR_FINFO_SIZE;
    while ((rv = apr_dir_read(&finfo, wanted, dir)) == APR_SUCCESS) {
        printf("%s\t%10"PRIu64"\n", finfo.name, (uint64_t)finfo.size);
    }
    if (!APR_STATUS_IS_ENOENT(rv)) {
        apr_fatal(rv);
    }

    // Clean up
    apr_dir_close(dir);
    apr_pool_destroy(pool);
    apr_terminate();
    return 0;
}

static void apr_fatal(apr_status_t rv)
{
    const int bufsize = 1000;
    char buf[bufsize+1];
    printf("APR Error %d: %s\n", rv, apr_strerror(rv, buf, bufsize));
    exit(1);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top