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

#define ASCII_MIN 0x21
#define ASCII_MAX 0x7e

#define DEFLT_SIZ 0x10

struct dump {
	char *buffer;
	int      len;
};

static void initDump(struct dump *d)
{
	d->buffer = calloc(DEFLT_SIZ, sizeof(char));
	d->len    = 0;
}


int main(int argc, char *argv[])
{
	FILE      *fp;
	char        c;
	struct dump d;
	int       min;  

	if (argc != 3)
	{
		printf("Usage: %s <minimum_lenght> <filename>", argv[0]);
		exit(EXIT_FAILURE);
	}
	min = strtol(argv[1], NULL, 10);
	if (!min)
	{
		printf("strtol failed, %s is an invalid number", argv[1]);
		exit(EXIT_FAILURE);
	}
	if ((fp = fopen(argv[2], "rb")) == NULL)
	{
		printf("open %s failed", argv[2]);
		exit(EXIT_FAILURE);
	}
	initDump(&d);
	while(fread(&c, sizeof(char), 1, fp))
	{
		if (c >= ASCII_MIN &&
		    c <= ASCII_MAX)
		{
			d.buffer[d.len] = c;
			d.len++;
			if (d.len >= DEFLT_SIZ - 1)
				d.buffer = realloc(d.buffer, d.len+1);
			d.buffer[d.len] = '\0';
		}
		else if ( d.len >= min)
		{
			printf("%s\n", d.buffer);
			memset(d.buffer, 0, d.len);
			d.len = 0;
		}
		else
		{
			memset(d.buffer, 0, d.len);
			d.len = 0;
		}
	}
	free(d.buffer);
	fclose(fp);

	return EXIT_SUCCESS;
}