/* FileToNumbers.c (c) Kari Laitinen http://www.naturalprogramming.com/ 2013-11-28 File created. 2013-11-28 Last modification. */ #include int main( int number_of_command_line_arguments, char* command_line_arguments[] ) { if ( number_of_command_line_arguments != 2 ) { printf( "\n You have to command this program as: \n" "\n FileToNumbers file.ext \n" ) ; } else { FILE *file_to_read ; file_to_read = fopen( command_line_arguments[ 1 ], "rb" ) ; if ( file_to_read == 0 ) { printf( "\n Cannot open %s", command_line_arguments[ 1 ] ) ; } else { while ( ! feof( file_to_read ) ) { char bytes_from_file[ 16 ] ; char byte_from_file ; int byte_counter = 0 ; // We'll use the fread() function so that it reads // one byte at a time from the file. while ( byte_counter < 16 && fread( &byte_from_file, 1, 1, file_to_read ) > 0 ) { bytes_from_file[ byte_counter ] = byte_from_file ; byte_counter ++ ; } int number_of_bytes_read = byte_counter ; char line_of_bytes[ 80 ] ; char bytes_as_characters[ 80 ] ; strcpy( line_of_bytes, "" ) ; strcpy( bytes_as_characters, "" ) ; int byte_index ; for ( byte_index = 0 ; byte_index < number_of_bytes_read ; byte_index ++ ) { char byte_as_string[ 8 ] ; sprintf( byte_as_string, " %02X", (unsigned char) bytes_from_file[ byte_index ] ) ; strcat( line_of_bytes, byte_as_string ) ; if ( bytes_from_file[ byte_index ] >= ' ' ) { bytes_as_characters[ byte_index ] = bytes_from_file[ byte_index ] ; } else { bytes_as_characters[ byte_index ] = ' ' ; } bytes_as_characters[ byte_index + 1 ] = 0 ; // terminate the string } printf( "\n%-48s %s", line_of_bytes, bytes_as_characters ) ; } fclose( file_to_read ) ; printf( "\n" ) ; } } }