Byte Count
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | //
// 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;
}
|
This is a small C program i wrote to count the occurrences of each byte in a file, the program supports up to 32 bit file sizes.
I do not know of much practical use for this program, it was just somthing i did as a fun short chalenge. I have only built this on OSX using GCC, and do not know if it will work on any other platforms.
if you have any feedback on this program please contact me.