Skip to content

Instantly share code, notes, and snippets.

@kylelk
Created November 16, 2014 21:07
Show Gist options
  • Save kylelk/d2e93a5589ab81bbdb14 to your computer and use it in GitHub Desktop.
Save kylelk/d2e93a5589ab81bbdb14 to your computer and use it in GitHub Desktop.
Counts the occurrences of each byte in a file
//
// main.c
// byte count
//
// Created by kyle kersey on 11/16/14.
// Copyright (c) 2014 kyle kersey. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int main(int argc, const char * argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: file name\n");
return 0;
}
/* get size of file */
struct stat st;
stat(argv[1], &st);
uint32_t file_size = st.st_size;
/* allocate memory for file contents */
unsigned char *file_contents;
file_contents = malloc(file_size);
/* open and read the file */
FILE *fp = fopen(argv[1], "rb");
if (fp == NULL) {
fprintf(stderr, "cannot open file '%s'\n", argv[1]);
return 0;
}
fread(file_contents, file_size, 1, fp);
fclose(fp);
/* array holding byte counts */
uint32_t byte_list[0xFF];
/* clear the array */
memset(byte_list, 0, sizeof(byte_list));
unsigned long file_index=0;
while (file_index<file_size) {
++byte_list[file_contents[file_index++]];
}
int i;
for (i=0; i<=0xFF; i++) {
printf("%02X %d\n", i, byte_list[i]);
}
/* clear alocated memory */
free(file_contents);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment