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