Skip to content

Instantly share code, notes, and snippets.

@UplinkCoder
Created February 14, 2022 20:34
Show Gist options
  • Save UplinkCoder/30e156c981fa98cf0e72e8c13f2c82da to your computer and use it in GitHub Desktop.
Save UplinkCoder/30e156c981fa98cf0e72e8c13f2c82da to your computer and use it in GitHub Desktop.
#pragma once
#include <stdint.h>
#include <stdlib.h>
#define MAIN int main (int argc, char* argv[])
#define RANGE(FROM, TO) for (int it = (FROM); it < (TO); it++)
#define FOR(E, RANGE_) \
for(auto& E = (RANGE_).begin(), const auto& __end = (RANGE).end(); \
E != __end(); \
E++)
#define ARRAY_SIZE(A) \
(sizeof((A)) / sizeof((A)[0]))
#define ZERO_MEM(MEM) \
RANGE(0, sizeof(*MEM)) \
{ ((uint8_t*)MEM)[it] = 0; }
#ifdef __linux__
# include <unistd.h>
# include <sys/stat.h>
# include <fcntl.h>
// ssize_t write(int fd, void *buf, size_t count);
ssize_t read(int fd, void *buf, size_t count);
// int open(const char *pathname, int flags);
# define STDERR(S) write(2, #S, sizeof(#S))
typedef struct File
{
int handle;
uint32_t size;
uint8_t* content;
} File;
File read_file(const char* path)
{
int fd = open(path, O_RDONLY);
uint32_t size = (fd ? lseek(fd, 0, SEEK_END) : 0);
uint8_t* content = malloc(size + 1);
if (fd) lseek(fd, 0, SEEK_SET);
ssize_t read_size = read(fd, content, size);
content[size] = '\0';
return (File) { .handle = fd, .size = size, .content = content };
}
# define READ_FILE(F, PATH) \
File F = read_file(PATH);
#else
#error ("Platform not supported");s
#endif
#include <errno.h>
#include <stdio.h>
typedef struct FreqRecord
{
uint8_t byte;
uint32_t freq;
} FreqRecord;
int FreqRecord_comp(const void* avp, const void* bvp)
{
const FreqRecord* ap = (FreqRecord*) avp;
const FreqRecord* bp = (FreqRecord*) bvp;
return bp->freq - ap->freq;
}
MAIN
{
if (argc != 2)
{
STDERR("this programm expects one argument exactly\n");
return -ENOENT;
}
READ_FILE(f, argv[1]);
FreqRecord byte_freq[256];
ZERO_MEM(&byte_freq);
if (!f.handle)
{
return -ENOENT;
}
{
for(int i = 0; i < ARRAY_SIZE(byte_freq); i++)
{
byte_freq[i].byte = i;
}
for(int i = 0; i < f.size; i++)
{
byte_freq[f.content[i]].freq++;
}
}
qsort(byte_freq, ARRAY_SIZE(byte_freq), sizeof(byte_freq[0]), FreqRecord_comp);
RANGE(0, ARRAY_SIZE(byte_freq))
{
FreqRecord r = byte_freq[it];
if (r.freq)
{
printf("\tfreq: %u, byte:%u '%c'\n", r.freq, r.byte, r.byte);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment