Example #1
0
File: array.c Project: fdotli/libu
/**
 *  \brief  Create a new array object
 *
 *  \param t        the type of the elements in this array, i.e. one of 
 *                  the standard C types (which have 1:1 mapping with 
 *                  \c U_ARRAY_TYPE_*'s) or a pointer type (select 
 *                  \c U_ARRAY_TYPE_PTR in this case)
 *  \param nslots   the initial number of slots to be created  (set it to \c 0 
 *                  if you want the default)
 *  \param pda      the newly created array object as a result argument
 *
 *  \retval  0  on success 
 *  \retval -1  on error
 */
int u_array_create (u_array_type_t t, size_t nslots, u_array_t **pda)
{
    u_array_t *da = NULL;
    size_t max_nslots;

    dbg_return_if (pda == NULL, -1);
    dbg_return_if (!U_ARRAY_TYPE_IS_VALID(t), -1);

    da = u_zalloc(sizeof(u_array_t));
    warn_err_sif (da == NULL);

    da->type = t;

    if (nslots == 0)
        da->nslots = U_ARRAY_NSLOTS_DFL;
    else if (nslots > (max_nslots = MAX_NSLOTS(da)))
        da->nslots = max_nslots;
    else
        da->nslots = nslots;

    da->base = u_zalloc(da->nslots * sizeof_type[da->type]);
    warn_err_sif (da->base == NULL);

    *pda = da;

    return 0;
err:
    u_array_free(da);
    return -1;
}
Example #2
0
/**
 * \brief  Fill a buffer object with the content of a file
 *
 * Open \a filename and copy its whole content into the given buffer.
 *
 * \param ubuf     buffer object
 * \param filename the source filename
 *
 * \return \c 0 on success, not zero on failure
 */
int u_buf_load(u_buf_t *ubuf, char *filename)
{
    enum { BUFSZ = 4096 };
    struct stat st;
    FILE *fp = NULL;

    dbg_err_if(ubuf == NULL);
    dbg_err_if(filename == NULL);

    dbg_err_if(stat(filename, &st));

    /* clear the current data */
    dbg_err_if(u_buf_clear(ubuf));

    /* be sure to have a big enough buffer */
    dbg_err_if(u_buf_reserve(ubuf, st.st_size));

    warn_err_sif((fp = fopen(filename, "r")) == NULL);

    /* fill the buffer with the whole file content */
    dbg_err_if(fread(ubuf->data, st.st_size, 1, fp) == 0);
    ubuf->len = st.st_size;

    fclose(fp);

    return 0;
err:
    if(fp)
        fclose(fp);
    return ~0;
}