git.y1.nz

gbdk-2020

GameBoy Development Kit
download: https://git.y1.nz/archives/gbdk.tar.gz
README | Files | Log | Refs | LICENSE

gbdk-support/makecom/files.c

      1 #include <stdio.h>
      2 #include <stdbool.h>
      3 #include <stdint.h>
      4 #include <stdlib.h>
      5 
      6 
      7 
      8 // Read from a file into a buffer (will allocate needed memory)
      9 // Returns NULL if reading file didn't succeed
     10 uint8_t * file_read_into_buffer(char * filename, uint32_t *ret_size) {
     11 
     12     long fsize;
     13     FILE * file_in = fopen(filename, "rb");
     14     uint8_t * filedata = NULL;
     15 
     16     if (file_in) {
     17         // Get file size
     18         fseek(file_in, 0, SEEK_END);
     19         fsize = ftell(file_in);
     20         if (fsize != -1L) {
     21             fseek(file_in, 0, SEEK_SET);
     22 
     23             filedata = malloc(fsize);
     24             if (filedata) {
     25                 if (fsize != fread(filedata, 1, fsize, file_in)) {
     26                     printf("makecom: Warning: File read size didn't match expected for %s\n", filename);
     27                     filedata = NULL;
     28                 }
     29                 // Read was successful, set return size
     30                 *ret_size = fsize;
     31             } else printf("makecom: ERROR: Failed to allocate memory to read file %s\n", filename);
     32 
     33         } else printf("makecom: ERROR: Failed to read size of file %s\n", filename);
     34 
     35         fclose(file_in);
     36     } else printf("makecom: ERROR: Failed to open input file %s\n", filename);
     37 
     38     return filedata;
     39 }
     40 
     41 
     42 
     43 // Writes a buffer to a file
     44 bool file_write_from_buffer(char * filename, uint8_t * p_buf, uint32_t data_len) {
     45 
     46     bool status = false;
     47     size_t wrote_bytes;
     48     FILE * file_out = fopen(filename, "wb");
     49     if (file_out) {
     50         if (data_len == fwrite(p_buf, 1, data_len, file_out))
     51             status = true;
     52         else
     53             printf("makecom: Warning: File write size didn't match expected for %s\n", filename);
     54 
     55         fclose(file_out);
     56     } else {
     57         printf("makecom: ERROR: Failed to open output file %s!\n",filename);
     58         exit(EXIT_FAILURE);
     59     }
     60 
     61     return status;
     62 }

This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.