ossp-pkg/cfg/cfg_util.c
/*
** OSSP cfg - Configuration Parsing
** Copyright (c) 2002-2006 Ralf S. Engelschall <rse@engelschall.com>
** Copyright (c) 2002-2006 The OSSP Project (http://www.ossp.org/)
**
** This file is part of OSSP cfg, a configuration parsing
** library which can be found at http://www.ossp.org/pkg/lib/cfg/.
**
** Permission to use, copy, modify, and distribute this software for
** any purpose with or without fee is hereby granted, provided that
** the above copyright notice and this permission notice appear in all
** copies.
**
** THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
** USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
** OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
** SUCH DAMAGE.
**
** cfg_util.c: utility functions
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "cfg.h"
#include "cfg_util.h"
#include "cfg_global.h"
cfg_rc_t cfg_util_readfile(const char *filename, char **buf_ptr, size_t *buf_size, size_t *buf_used)
{
FILE *fp = NULL;
size_t n;
char *cp;
if (strcmp(filename, "-") == 0) {
/* file is given on stdin */
(*buf_size) = 32;
if ((*buf_ptr = (char *)malloc(*buf_size)) == NULL)
return CFG_ERR_SYS;
cp = *buf_ptr;
while ((n = fread(cp, 1, (*buf_size)-(cp-(*buf_ptr)), stdin)) > 0) {
cp += n;
if (((*buf_ptr)+(*buf_size))-cp < (*buf_size)/8) {
(*buf_size) *= 2;
n = cp-(*buf_ptr);
if ((cp = (char *)realloc(*buf_ptr, *buf_size)) == NULL) {
free(*buf_ptr);
return CFG_ERR_SYS;
}
*buf_ptr = cp;
cp += n;
}
}
*cp = '\0';
*buf_used = (cp - *buf_ptr);
}
else {
/* file is given on filesystem */
if ((fp = fopen(filename, "r")) == NULL)
return CFG_ERR_SYS;
fseek(fp, 0, SEEK_END);
if ((n = ftell(fp)) > 0) {
if ((*buf_ptr = (char *)malloc(n+1)) == NULL) {
fclose(fp);
return CFG_ERR_SYS;
}
fseek(fp, 0, SEEK_SET);
if ((n = fread(*buf_ptr, 1, n, fp)) == 0) {
free(*buf_ptr);
fclose(fp);
return CFG_ERR_SYS;
}
(*buf_ptr)[n] = '\0';
(*buf_size) = n+1;
(*buf_used) = n;
}
else {
(*buf_ptr) = strdup("");
(*buf_size) = 1;
(*buf_used) = 0;
}
fclose(fp);
}
return CFG_OK;
}