[PATCH 2/3] fwts: Add file_open_and_read_binary

Colin Ian King colin.king at canonical.com
Tue May 26 08:49:04 UTC 2015


On 21/05/15 08:15, Jeremy Kerr wrote:
> Add a function to open and read a binary file in a single chunk.
> 
> Signed-off-by: Jeremy Kerr <jk at ozlabs.org>
> 
> ---
>  src/lib/include/fwts_fileio.h |    1 
>  src/lib/src/fwts_fileio.c     |   45 ++++++++++++++++++++++++++++++++++
>  2 files changed, 46 insertions(+)
> 
> diff --git a/src/lib/include/fwts_fileio.h b/src/lib/include/fwts_fileio.h
> index 33b727b..e9fdced 100644
> --- a/src/lib/include/fwts_fileio.h
> +++ b/src/lib/include/fwts_fileio.h
> @@ -24,5 +24,6 @@
>  
>  fwts_list* fwts_file_read(FILE *fp);
>  fwts_list* fwts_file_open_and_read(const char *file);
> +int fwts_file_open_and_read_binary(const char *file, char **buf, size_t *len);
>  
>  #endif
> diff --git a/src/lib/src/fwts_fileio.c b/src/lib/src/fwts_fileio.c
> index ca99631..5875a32 100644
> --- a/src/lib/src/fwts_fileio.c
> +++ b/src/lib/src/fwts_fileio.c
> @@ -17,6 +17,7 @@
>   *
>   */
>  
> +#include <assert.h>
>  #include <stdio.h>
>  #include <stdlib.h>
>  #include <string.h>
> @@ -61,3 +62,47 @@ fwts_list* fwts_file_open_and_read(const char *file)
>  
>  	return list;
>  }
> +
> +int fwts_file_open_and_read_binary(const char *file, char **buf, size_t *len)
> +{
> +	size_t tmplen;
> +	char *tmpbuf;
> +	long pos;
> +	FILE *fp;
> +	int rc;
> +
> +	if ((fp = fopen(file, "rb")) == NULL)
> +		return FWTS_ERROR;
> +
> +	rc = fseek(fp, 0, SEEK_END);
> +	if (rc) {
> +		rc = FWTS_ERROR;
> +		goto out;
> +	}
> +
> +	pos = ftell(fp);
> +	if (pos < 0) {
> +		rc = FWTS_ERROR;
> +		goto out;
> +	}
> +
> +	rewind(fp);
> +
> +	tmpbuf = malloc(pos);
> +	assert(tmpbuf);

.. as before, I'd prefer not to have asserts

> +
> +	tmplen = fread(tmpbuf, 1, pos, fp);
> +	if (tmplen != (size_t)pos) {
> +		free(tmpbuf);
> +		rc = FWTS_ERROR;
> +		goto out;
> +	}
> +
> +	rc = FWTS_OK;
> +	*buf = tmpbuf;
> +	*len = tmplen;
> +
> +out:
> +	fclose(fp);
> +	return rc;
> +}
> 




More information about the fwts-devel mailing list