comparison th_ioctx.c @ 67:d94af48cef7b

Added new module, a simple I/O context helper.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 15 Nov 2012 19:21:14 +0200
parents
children ce49160d2599
comparison
equal deleted inserted replaced
66:34d58b0f2d52 67:d94af48cef7b
1 /*
2 * Standard I/O context helpers
3 * Programmed and designed by Matti 'ccr' Hamalainen
4 * (C) Copyright 2012 Tecnic Software productions (TNSP)
5 *
6 * Please read file 'COPYING' for information on license and distribution.
7 */
8 #include "th_ioctx.h"
9 #include "th_string.h"
10
11 /* Simple STD I/O contexts
12 */
13 BOOL th_ioctx_init(th_ioctx_t *ctx, const char *filename)
14 {
15 if (ctx == NULL || filename == NULL)
16 return FALSE;
17
18 th_memset(&ctx, 0, sizeof(ctx));
19 if ((ctx->filename = th_strdup(filename)) == NULL)
20 return FALSE;
21
22 return TRUE;
23 }
24
25
26 BOOL th_ioctx_open(th_ioctx_t *ctx, const char *filename, const char *mode)
27 {
28 if (!th_ioctx_init(ctx, filename) || mode == NULL)
29 return FALSE;
30
31 if ((ctx->fp = fopen(filename, mode)) == NULL)
32 return FALSE;
33
34 return TRUE;
35 }
36
37
38 void th_ioctx_close(th_ioctx_t *ctx)
39 {
40 if (ctx != NULL)
41 {
42 th_free(ctx->filename);
43 ctx->filename = NULL;
44
45 if (ctx->fp != NULL)
46 fclose(ctx->fp);
47 ctx->fp = NULL;
48 }
49 }
50
51
52 void th_ioctx_error(th_ioctx_t *ctx, const int err, const char *fmt, ...)
53 {
54 char *msg;
55 va_list ap;
56
57 va_start(ap, fmt);
58 msg = th_strdup_vprintf(fmt, ap);
59 va_end(ap);
60
61 if (ctx->error != NULL)
62 ctx->error(ctx, err, msg);
63 else
64 THERR("'%s' #%d: %s\n", ctx->filename, (unsigned int) ctx->line, msg);
65
66 th_free(msg);
67 }
68
69
70 th_ioctx_t *th_ioctx_new(const char *filename)
71 {
72 th_ioctx_t *ctx = th_malloc0(sizeof(th_ioctx_t));
73 if (ctx == NULL)
74 return NULL;
75
76 th_ioctx_init(ctx, filename);
77 ctx->allocated = TRUE;
78 return ctx;
79 }
80
81
82 void th_ioctx_free(th_ioctx_t *ctx)
83 {
84 th_ioctx_close(ctx);
85
86 if (ctx->allocated)
87 th_free(ctx);
88 }