Project

General

Profile

Bug #1242 » dmpf.cpp

Robin Mills, 11 Oct 2016 20:35

 
1
#include <stdio.h>
2
#include <string.h>
3

    
4
static enum
5
{	errorOK = 0
6
, 	errorSyntax 
7
,   errorProcessing
8
} error = errorOK ;
9

    
10
void syntax()
11
{
12
	printf("syntax: dmpf [-option]+ filename\n") ;
13
}
14

    
15
bool printable(unsigned char c) { return c >= 32 && c <= 127 && c != '.' ; } 
16

    
17
int main(int argc, char* argv[])
18
{
19
	char* filename = argv[1] ;
20
	FILE* f = NULL ;
21
	
22
//  GCC_PREFIX_HEADER = dmpf.pch
23
//	GCC_PRECOMPILE_PREFIX_HEADER = YES
24
//	printf("engineer = %s\n",ENGINEER) ; // compiled in by dmpf.pch
25

    
26
	
27
	if ( argc < 2 ) {
28
		syntax() ;
29
		error = errorSyntax ;
30
	}
31
	
32
	if ( !error ) {
33
		f = strcmp(filename,"-") ? fopen(filename,"rb") : stdin ;
34
		if ( !f ) {
35
			printf("unable to open file %s\n",filename) ;
36
			error = errorProcessing ;
37
		}
38
	}
39
	
40
	if ( !error  )
41
	{
42
		char line[1000] ;
43
		char buff[16]   ;
44
		int  n          ;
45
		int count = 0   ;
46
		while ( (n = fread(buff,1,sizeof buff,f)) > 0 )
47
		{
48
			// line number
49
			int l = sprintf(line,"%#6x %6d: ",count,count ) ;
50
			count += n ;
51
			
52
			// ascii print
53
			for ( int i = 0 ; i < n ; i++ )
54
			{
55
				char c = buff[i] ;
56
		        l += sprintf(line+l,"%c", printable(c) ? c : '.' ) ;
57
			}
58
			// blank pad the ascii
59
			int save = n ;
60
			while ( n++ < sizeof(buff) ) l += sprintf(line+l," ") ;
61
			n = save     ;
62
			
63
		    // hex code
64
		    l += sprintf(line+l,"  -> ") ;
65
			for ( int i = 0 ; i < n ; i++ )
66
			{
67
				unsigned char c = buff[i] ;
68
				l += sprintf(line+l,printable(c) ? "  %c" : " %02x" ,c) ;
69
			}
70
			
71
			line[l] = 0 ;
72
			printf("%s\n",line) ;
73
		}
74
	}
75
	
76
	return error ;
77
}
(3-3/6)