Archived
1
0
Fork 0
This repository has been archived on 2024-03-16. You can view files and clone it, but cannot push or open issues or pull requests.
libg1m/src/handle.c
2016-10-30 20:18:15 +01:00

86 lines
2.1 KiB
C

/* ************************************************************************** */
/* _____ _ */
/* handle.c |_ _|__ _ _| |__ ___ _ _ */
/* | Project : libg1m | |/ _ \| | | | '_ \ / _ \ | | | */
/* | | (_) | |_| | | | | __/ |_| | */
/* By: thomas <thomas@touhey.fr> |_|\___/ \__,_|_| |_|\___|\__, |.fr */
/* Last updated: 2016/09/04 00:09:47 |___/ */
/* */
/* ************************************************************************** */
#include <libg1m/internals.h>
#include <stdio_ext.h>
#include <stdlib.h>
/**
* g1m_fopen:
* Open handle using FILE* pointer.
*
* @arg handle the handle to create
* @arg stream the stream
* @return the error code (0 if ok)
*/
int g1m_fopen(g1m_t **handle, FILE *stream)
{
int err;
/* check stream */
if (!stream) return (g1m_error_nostream);
if (!__freadable(stream)) return (g1m_error_noread);
/* seek to beginning */
if (fseek(stream, 0L, SEEK_SET)) return (g1m_error_noseek);
/* create the handle */
*handle = malloc(sizeof(g1m_t));
if (!*handle) return (g1m_error_alloc);
(*handle)->stream = stream;
/* fill it by parsing opened file */
if ((err = g1m_parse(*handle))) {
free(*handle);
*handle = NULL;
return (err);
}
/* everything ok */
return (0);
}
/**
* g1m_open:
* Open handle using path.
*
* @arg handle the handle to create.
* @arg path the path of the file to open.
* @return the error code (0 if ok).
*/
int g1m_open(g1m_t **handle, const char *path)
{
/* open stream */
FILE *f = fopen(path, "r+");
if (!f) return (g1m_error_errno);
/* open using `g1m_fopen` */
int err;
if ((err = g1m_fopen(handle, f)))
fclose(f);
return (err);
}
/**
* g1m_close:
* Close handle using path.
*
* @arg handle the handle to close.
* @return the error code (0 if ok).
*/
void g1m_close(g1m_t *handle)
{
/* close stream */
fclose(handle->stream);
free(handle);
}