github.com/cellofellow/gopkg@v0.0.0-20140722061823-eec0544a62ad/image/webp/libwebp/examples/example_util.c (about)

     1  // Copyright 2012 Google Inc. All Rights Reserved.
     2  //
     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.
     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  
    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) {
    45      fprintf(stderr, "Could not read %d bytes of data from file %s\n",
    46              (int)file_size, file_name);
    47      free(file_data);
    48      return 0;
    49    }
    50    *data = (uint8_t*)file_data;
    51    *data_size = file_size;
    52    return 1;
    53  }
    54  
    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