Code:
#include <stdio.h>
#include <stdlib.h>
int cmp( const void* a, const void* b ) {
return ( *(char*)a - *(char*)b );
}
void make_header( char* bytes, int count, int size, FILE* o ) {
int i;
char tmp;
for ( i = 0; i < count; i++ ) {
if ( bytes[i] != '\0' && bytes[i] != '-' ) {
if ( i + 1 == count )
fwrite( &bytes[i], 1, 1, o );
else if ( bytes[i] == bytes[i - 1] + 1 && bytes[i] != bytes[i + 1] - 1 )
fwrite( &bytes[i], 1, 1, o );
else if ( bytes[i] != bytes[i - 1] + 1 && bytes[i] == bytes[i + 1] - 1 ) {
fwrite( &bytes[i], 1, 1, o );
fwrite( "-", 1, 1, o );
}
} else {
if ( i + 1 == count ) {
fwrite( "\0", 1, 1, o );
fwrite( &bytes[i], 1, 1, o );
} else if ( bytes[i] == bytes[i - 1] + 1 && bytes[i] != bytes[i + 1] - 1 ) {
fwrite( "\0", 1, 1, o );
fwrite( &bytes[i], 1, 1, o );
} else if ( bytes[i] != bytes[i - 1] + 1 && bytes[i] == bytes[i + 1] - 1 ) {
fwrite( "\0", 1, 1, o );
fwrite( &bytes[i], 1, 1, o );
fwrite( "-", 1, 1, o );
}
}
}
fwrite( "\0\1", 1, 2, o );
i = 4;
while ( i-- > 0 ) {
tmp = ( size >> ( 8 * i ) ) & 0xFF;
fwrite( &tmp, 1, 1, o );
}
}
int main( int argc, char** argv ) {
FILE* f = fopen( "1.txt", "rb" );
if ( !f ) {
perror( "Failed to open input file" );
exit( 1 );
}
FILE* o = fopen( "1.bin", "wb" );
if ( !o ) {
perror( "Failed to open output file" );
exit( 1 );
}
char bytes[256] = {0},
revbytes[256] = {0},
curbyte[1] = {0};
int numbytes = 0,
i = 0;
while ( fread( curbyte, 1, 1, f ) ) {
for ( i = 0; i < numbytes; i++ )
if ( bytes[i] == curbyte[0] ) {
i = 257;
break;
}
if ( i != 257 ) {
bytes[numbytes] = curbyte[0];
numbytes++;
}
}
qsort( bytes, numbytes, sizeof( char ), cmp );
fseek( f, 0, SEEK_END );
make_header( bytes, numbytes, ftell( f ), o );
rewind( f );
for ( i = 0; i < numbytes; i++ )
revbytes[(int)bytes[i]] = i;
// We need a 2048-bit integer to continue past this point easily.
return 0;
}