int bestCode( WordList *wordList, char const *str ) { Word* match = bsearch(str, wordList->words, wordList->len, sizeof(Word), myComp); // int index = 0; if (match) { for (int i = 0; i < (wordList->len); i++){ if (strcmp(*match, (wordList->words[i])) == 0){ //printf("here i: %d\n", i); return i; } } } else { int oldLen = strlen(str); if (oldLen > WORD_MAX){ oldLen = WORD_MAX; } char newStr[oldLen]; strncpy(newStr, str, oldLen); newStr[oldLen - 1] = '\0'; // printf("%s \n", newStr); return bestCode(wordList, newStr); } //if it gets here, something has gone horribly wrong. return 0; }
/** Opens appropriate files and handles them @param argc number of command line arguments @param argv array of command line arguments @return the exit status of the program */ int main( int argc, char *argv[] ) { char *wordFile = "words.txt"; FILE *input; FILE *output; if ( argc < 3 || argc > 4 ) { fprintf( stderr, "usage: pack <input.txt> <compressed.raw> [wordfile.txt]\n" ); exit( 1 ); } input = fopen( argv[ 1 ], "rb" ); if ( !input ) { printf( "usage: readFile <input-file>\n" ); exit( 1 ); } output = fopen( argv[ 2 ], "rw" ); if ( !output ) { printf( "usage: readFile <input-file>\n" ); exit( 1 ); } if ( argc == 4 ) { wordFile = argv[ 3 ]; } WordList *wordList = readWordList( wordFile ); #ifdef DEBUG // Report the entire contents of the word list, once it's built. printf( "---- word list -----\n" ); for ( int i = 0; i < wordList->len; i++ ) printf( "%d == %s\n", i, wordList->words[ i ] ); printf( "--------------------\n" ); #endif // ... // Read the contents of the whole file into one big buffer. This could be more // efficient, but it simplifies the rest of the program. char *buffer = readFile( input ); // Write out codes for everything in the buffer. int pos = 0; PendingBits pending = { 0, 0 }; while ( buffer[ pos ] ) { // Get the next code. int code = bestCode( wordList, buffer + pos ); #ifdef DEBUG printf( "%d <- %s\n", code, wordList->words[ code ] ); #endif // Write it out and move ahead by the number of characters we just encoded. readCode( &pending, input ); pos += strlen( wordList->words[ code ] ); } // Write out any remaining bits in the last, partial byte. flushBits( &pending, output ); // ... fclose( input ); fclose( output ); return EXIT_SUCCESS; }