Browse Source

Simplify error handling in util module

Use die-on-error memory-allocating functions, and use assert()
to check for arguments validity. Passing a NULL pointer to anyone
of these functions is a programming error anyway, not a runtime
error.
master
Damien Goutte-Gattat 5 years ago
parent
commit
863bb92f1a
  1. 38
      src/util.c

38
src/util.c

@ -23,12 +23,14 @@
#include "util.h"
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <xmem.h>
/**
* Checks if the specified file exists.
*
@ -41,10 +43,7 @@ file_exists(const char *path)
{
struct stat st;
if ( ! path ) {
errno = EINVAL;
return -1;
}
assert(path != NULL);
return stat(path, &st);
}
@ -62,10 +61,7 @@ get_file_size(FILE *f)
{
long s;
if ( ! f ) {
errno = EINVAL;
return -1;
}
assert(f != NULL);
if ( fseek(f, 0, SEEK_END) == -1
|| (s = ftell(f)) == -1
@ -93,10 +89,7 @@ read_file(const char *filename, size_t *len, size_t max)
FILE *f;
unsigned char *blob = NULL;
if ( ! filename ) {
errno = EINVAL;
return NULL;
}
assert(filename != NULL);
if ( (f = fopen(filename, "r")) ) {
long size;
@ -106,7 +99,8 @@ read_file(const char *filename, size_t *len, size_t max)
if ( max != 0 && (unsigned long) size > max )
errno = EFBIG;
else if ( (blob = malloc(size)) ) {
else {
blob = xmalloc(size);
if ( (nread = fread(blob, 1, size, f)) < (unsigned long) size ) {
free(blob);
blob = NULL;
@ -138,10 +132,8 @@ write_file(const char *filename, const unsigned char *contents, size_t len)
FILE *f;
int rc;
if ( ! filename || ! contents ) {
errno = EINVAL;
return -1;
}
assert(filename != NULL);
assert(contents != NULL);
if ( (f = fopen(filename, "w")) ) {
rc = fwrite(contents, sizeof(char), len, f) == len ? 0 : -1;
@ -156,8 +148,7 @@ write_file(const char *filename, const unsigned char *contents, size_t len)
*
* @param path The path to extract the basename from.
*
* @return A newly allocated buffer containing the basename,
* or NULL if an error occured (check errno for details).
* @return A newly allocated buffer containing the basename.
*/
char *
get_file_basename(const char *path)
@ -165,10 +156,7 @@ get_file_basename(const char *path)
char *last_slash, *last_dot;
unsigned n;
if ( ! path ) {
errno = EINVAL;
return NULL;
}
assert(path != NULL);
if ( (last_slash = strrchr(path, '/')) )
path = last_slash + 1;
@ -178,5 +166,5 @@ get_file_basename(const char *path)
else
n = strlen(path);
return strndup(path, n);
return xstrndup(path, n);
}

Loading…
Cancel
Save