James Zern | 061263a | 2012-05-11 16:00:57 -0700 | [diff] [blame] | 1 | // Copyright 2012 Google Inc. All Rights Reserved. |
| 2 | // |
James Zern | d640614 | 2013-06-06 23:05:58 -0700 | [diff] [blame] | 3 | // 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 Zern | 061263a | 2012-05-11 16:00:57 -0700 | [diff] [blame] | 8 | // ----------------------------------------------------------------------------- |
| 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 | |
James Zern | 061263a | 2012-05-11 16:00:57 -0700 | [diff] [blame] | 17 | // ----------------------------------------------------------------------------- |
| 18 | // File I/O |
| 19 | |
| 20 | int ExUtilReadFile(const char* const file_name, |
| 21 | const uint8_t** data, size_t* data_size) { |
| 22 | int ok; |
| 23 | void* file_data; |
| 24 | size_t file_size; |
| 25 | FILE* in; |
| 26 | |
| 27 | if (file_name == NULL || data == NULL || data_size == NULL) return 0; |
| 28 | *data = NULL; |
| 29 | *data_size = 0; |
| 30 | |
| 31 | in = fopen(file_name, "rb"); |
| 32 | if (in == NULL) { |
| 33 | fprintf(stderr, "cannot open input file '%s'\n", file_name); |
| 34 | return 0; |
| 35 | } |
| 36 | fseek(in, 0, SEEK_END); |
| 37 | file_size = ftell(in); |
| 38 | fseek(in, 0, SEEK_SET); |
| 39 | file_data = malloc(file_size); |
| 40 | if (file_data == NULL) return 0; |
| 41 | ok = (fread(file_data, file_size, 1, in) == 1); |
| 42 | fclose(in); |
| 43 | |
| 44 | if (!ok) { |
James Zern | 14d42af | 2013-03-20 16:59:35 -0700 | [diff] [blame] | 45 | fprintf(stderr, "Could not read %d bytes of data from file %s\n", |
| 46 | (int)file_size, file_name); |
James Zern | 061263a | 2012-05-11 16:00:57 -0700 | [diff] [blame] | 47 | free(file_data); |
| 48 | return 0; |
| 49 | } |
| 50 | *data = (uint8_t*)file_data; |
| 51 | *data_size = file_size; |
| 52 | return 1; |
| 53 | } |
| 54 | |
Urvang Joshi | e9a15a3 | 2012-11-07 14:41:15 -0800 | [diff] [blame] | 55 | int ExUtilWriteFile(const char* const file_name, |
| 56 | const uint8_t* data, size_t data_size) { |
| 57 | int ok; |
| 58 | FILE* out; |
| 59 | |
| 60 | if (file_name == NULL || data == NULL) { |
| 61 | return 0; |
| 62 | } |
| 63 | out = fopen(file_name, "wb"); |
| 64 | if (out == NULL) { |
| 65 | fprintf(stderr, "Error! Cannot open output file '%s'\n", file_name); |
| 66 | return 0; |
| 67 | } |
| 68 | ok = (fwrite(data, data_size, 1, out) == 1); |
| 69 | fclose(out); |
| 70 | return ok; |
| 71 | } |
| 72 | |