Github User Fetcher 1.0.0
C Application with Server and GUI
Loading...
Searching...
No Matches
duktape-1.5.2/examples/eventloop/fileio.c
Go to the documentation of this file.
1/*
2 * File I/O binding example.
3 */
4
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8
9#include "duktape.h"
10
11static int fileio_readfile(duk_context *ctx) {
12 const char *filename = duk_to_string(ctx, 0);
13 FILE *f = NULL;
14 long len;
15 void *buf;
16 size_t got;
17
18 if (!filename) {
19 goto error;
20 }
21
22 f = fopen(filename, "rb");
23 if (!f) {
24 goto error;
25 }
26
27 if (fseek(f, 0, SEEK_END) != 0) {
28 goto error;
29 }
30
31 len = ftell(f);
32
33 if (fseek(f, 0, SEEK_SET) != 0) {
34 goto error;
35 }
36
37 buf = duk_push_fixed_buffer(ctx, (size_t) len);
38
39 got = fread(buf, 1, len, f);
40 if (got != (size_t) len) {
41 goto error;
42 }
43
44 fclose(f);
45 f = NULL;
46
47 return 1;
48
49 error:
50 if (f) {
51 fclose(f);
52 }
53
54 return DUK_RET_ERROR;
55}
56
58 { "readfile", fileio_readfile, 1 },
59 { NULL, NULL, 0 }
60};
61
63 /* Set global 'FileIo'. */
65 duk_push_object(ctx);
67 duk_put_prop_string(ctx, -2, "FileIo");
68 duk_pop(ctx);
69}
void fileio_register(duk_context *ctx)
static duk_function_list_entry fileio_funcs[]
static int fileio_readfile(duk_context *ctx)
DUK_EXTERNAL duk_bool_t duk_put_prop_string(duk_context *ctx, duk_idx_t obj_idx, const char *key)
DUK_EXTERNAL duk_idx_t duk_push_object(duk_context *ctx)
DUK_EXTERNAL void duk_push_global_object(duk_context *ctx)
DUK_EXTERNAL void duk_put_function_list(duk_context *ctx, duk_idx_t obj_index, const duk_function_list_entry *funcs)
DUK_EXTERNAL const char * duk_to_string(duk_context *ctx, duk_idx_t index)
DUK_EXTERNAL void duk_pop(duk_context *ctx)
#define duk_push_fixed_buffer(ctx, size)
#define NULL
Definition gmacros.h:924
static void error(LoadState *S, const char *why)
size_t fread(void *, size_t, size_t, FILE *)