xref: /illumos-gate/usr/src/lib/libsqlite/tool/showdb.c (revision 8119dad84d6416f13557b0ba8e2aaf9064cbcfd3)
1 /*
2 ** A utility for printing all or part of an SQLite database file.
3 */
4 #include <stdio.h>
5 #include <ctype.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 
12 
13 static int pagesize = 1024;
14 static int db = -1;
15 static int mxPage = 0;
16 
17 static void out_of_memory(void){
18   fprintf(stderr,"Out of memory...\n");
19   exit(1);
20 }
21 
22 static print_page(int iPg){
23   unsigned char *aData;
24   int i, j;
25   aData = malloc(pagesize);
26   if( aData==0 ) out_of_memory();
27   lseek(db, (iPg-1)*pagesize, SEEK_SET);
28   read(db, aData, pagesize);
29   fprintf(stdout, "Page %d:\n", iPg);
30   for(i=0; i<pagesize; i += 16){
31     fprintf(stdout, " %03x: ",i);
32     for(j=0; j<16; j++){
33       fprintf(stdout,"%02x ", aData[i+j]);
34     }
35     for(j=0; j<16; j++){
36       fprintf(stdout,"%c", isprint(aData[i+j]) ? aData[i+j] : '.');
37     }
38     fprintf(stdout,"\n");
39   }
40   free(aData);
41 }
42 
43 int main(int argc, char **argv){
44   struct stat sbuf;
45   if( argc<2 ){
46     fprintf(stderr,"Usage: %s FILENAME ?PAGE? ...\n", argv[0]);
47     exit(1);
48   }
49   db = open(argv[1], O_RDONLY);
50   if( db<0 ){
51     fprintf(stderr,"%s: can't open %s\n", argv[0], argv[1]);
52     exit(1);
53   }
54   fstat(db, &sbuf);
55   mxPage = sbuf.st_size/pagesize + 1;
56   if( argc==2 ){
57     int i;
58     for(i=1; i<=mxPage; i++) print_page(i);
59   }else{
60     int i;
61     for(i=2; i<argc; i++){
62       int iStart, iEnd;
63       char *zLeft;
64       iStart = strtol(argv[i], &zLeft, 0);
65       if( zLeft && strcmp(zLeft,"..end")==0 ){
66         iEnd = mxPage;
67       }else if( zLeft && zLeft[0]=='.' && zLeft[1]=='.' ){
68         iEnd = strtol(&zLeft[2], 0, 0);
69       }else{
70         iEnd = iStart;
71       }
72       if( iStart<1 || iEnd<iStart || iEnd>mxPage ){
73         fprintf(stderr,
74           "Page argument should be LOWER?..UPPER?.  Range 1 to %d\n",
75           mxPage);
76         exit(1);
77       }
78       while( iStart<=iEnd ){
79         print_page(iStart);
80         iStart++;
81       }
82     }
83   }
84   close(db);
85 }
86