blob: 8d31da6686fdaccf863aedeaf7e5ebcd18f58ba3 [file] [log] [blame]
James Zern061263a2012-05-11 16:00:57 -07001// Copyright 2012 Google Inc. All Rights Reserved.
2//
James Zernd6406142013-06-06 23:05:58 -07003// Use of this source code is governed by a BSD-style license
4// that can be found in the COPYING file in the root of the source
5// tree. An additional intellectual property rights grant can be found
6// in the file PATENTS. All contributing project authors may
7// be found in the AUTHORS file in the root of the source tree.
James Zern061263a2012-05-11 16:00:57 -07008// -----------------------------------------------------------------------------
9//
10// Utility functions used by the example programs.
11//
12
13#include "./example_util.h"
14#include <stdio.h>
15#include <stdlib.h>
16
17#if defined(__cplusplus) || defined(c_plusplus)
18extern "C" {
19#endif
20
21// -----------------------------------------------------------------------------
22// File I/O
23
24int ExUtilReadFile(const char* const file_name,
25 const uint8_t** data, size_t* data_size) {
26 int ok;
27 void* file_data;
28 size_t file_size;
29 FILE* in;
30
31 if (file_name == NULL || data == NULL || data_size == NULL) return 0;
32 *data = NULL;
33 *data_size = 0;
34
35 in = fopen(file_name, "rb");
36 if (in == NULL) {
37 fprintf(stderr, "cannot open input file '%s'\n", file_name);
38 return 0;
39 }
40 fseek(in, 0, SEEK_END);
41 file_size = ftell(in);
42 fseek(in, 0, SEEK_SET);
43 file_data = malloc(file_size);
44 if (file_data == NULL) return 0;
45 ok = (fread(file_data, file_size, 1, in) == 1);
46 fclose(in);
47
48 if (!ok) {
James Zern14d42af2013-03-20 16:59:35 -070049 fprintf(stderr, "Could not read %d bytes of data from file %s\n",
50 (int)file_size, file_name);
James Zern061263a2012-05-11 16:00:57 -070051 free(file_data);
52 return 0;
53 }
54 *data = (uint8_t*)file_data;
55 *data_size = file_size;
56 return 1;
57}
58
Urvang Joshie9a15a32012-11-07 14:41:15 -080059int ExUtilWriteFile(const char* const file_name,
60 const uint8_t* data, size_t data_size) {
61 int ok;
62 FILE* out;
63
64 if (file_name == NULL || data == NULL) {
65 return 0;
66 }
67 out = fopen(file_name, "wb");
68 if (out == NULL) {
69 fprintf(stderr, "Error! Cannot open output file '%s'\n", file_name);
70 return 0;
71 }
72 ok = (fwrite(data, data_size, 1, out) == 1);
73 fclose(out);
74 return ok;
75}
76
James Zern061263a2012-05-11 16:00:57 -070077#if defined(__cplusplus) || defined(c_plusplus)
78} // extern "C"
79#endif