Inspired by this question I thought I provide my implementation. I tried to go with the spirit of the *nix tool chain - read from stdin and write to stdout. This has the added benefit of making buffering very easy (current and previous characters and the count).
All kinds of reviews welcome (best practices, error handling, weird edge cases, potential bugs or other pitfalls).
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
void write_char(int c)
{
if (EOF == putchar(c))
{
if (ferror(stdout))
{
perror("error writing char to stdout");
exit(EXIT_FAILURE);
}
}
}
void write_count(uint64_t count)
{
if (printf("%ull", count) < 0)
{
perror("error writing character count to stdout");
exit(EXIT_FAILURE);
}
}
int main(int argc, char** argv)
{
int current_char = 0;
int previous_char = 0;
uint64_t current_char_count = 0;
while (EOF != (current_char = getchar())
{
if (current_char_count == 0 || current_char_count == UINT64_MAX || previous_char != current_char)
{
if (current_char_count > 0)
{
write_count(current_char_count);
}
write_char(current_char);
current_char_count = 1;
previous_char = current_char;
}
else
{
current_char_count += 1;
}
}
}