#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <errno.h>
#include <string.h>

// Reads file "fname" into memory, using realloc to
// allocate space for it.  NULL-terminates, returns it.
char *ReadFile(char *fname);
int CountChar(char *content, char c);

int main(int argc, char **argv) {
  char *filecontent;

  // Make sure user passed in a command line argument.
  assert(argc == 2);

  // Read the contents of file argv[1] into memory.
  filecontent = ReadFile(argv[1]);
  assert(filecontent != NULL);

  // Count how many times the character 'X' occurs in the file.
  printf("%d\n", CountChar(filecontent, 'X'));

  // Clean up and return.
  free(filecontent);
  return EXIT_SUCCESS;
}


#define READSIZE 1000
char *ReadFile(char *fname) {
  char *buf = NULL;
  FILE *f;
  int readlen, count = 0;

  // Open up the file.
  f = fopen(fname, "rb");
  if (f == NULL)
    return NULL;

  // Slurp in the file, READSIZE bytes at a time.
  buf = (char *) realloc(buf, READSIZE);
  assert(buf != NULL);
  while ((readlen = fread(buf+count, 1, READSIZE, f)) > 0) {
    count += readlen;
    buf = (char *) realloc(buf, count + READSIZE);
    assert(buf != NULL);
  }

  // Did we break because of an error?
  if (ferror(f)) {
    // Yes, so clean up and arrange to return NULL.
    free(buf);
    buf = NULL;
    count = 0;
  }

  fclose(f);
  return buf;
}

int CountChar(char *content, char c) {
  int i, count = 0;

  for (i = 0; i < strlen(content); i++) {
    if (content[i] == c)
      count++;
  }
  return count;
}