headview.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #include <stdio.h>
  2. #ifdef unix
  3. #include <unistd.h>
  4. #endif
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <ctype.h>
  8. #include <fcntl.h>
  9. #ifdef WIN32
  10. #include <io.h>
  11. #endif
  12. #define BUFLEN 64
  13. #define ENDOFSTR ('\0')
  14. static void showbytes(int thisbuflen, int thisstart,char *buffer);
  15. int main(int argc,char *argv[])
  16. {
  17. int fh;
  18. int buflen = BUFLEN, bufcnt, bytescnt, partsect, n, thisbuflen, thisstart;
  19. char buffer[BUFLEN];
  20. if(argc != 3) {
  21. fprintf(stderr,"USAGE: headview filename bytescnt\n");
  22. return 0;
  23. }
  24. if(sscanf(argv[2],"%d",&bytescnt) < 1) {
  25. fprintf(stderr,"Cannot read bytescnt\n");
  26. return 0;
  27. }
  28. if(bytescnt <= 0) {
  29. fprintf(stderr,"Invalid bytescnt\n");
  30. return 0;
  31. }
  32. #ifdef WIN32
  33. if((fh = open(argv[1],O_RDONLY|O_RAW,0))<0) {
  34. #else
  35. if((fh = open(argv[1],O_RDONLY,0))<0) {
  36. #endif
  37. fprintf(stderr,"Cannot open file %s\n",argv[1]);
  38. return 0;
  39. }
  40. bufcnt = bytescnt/buflen;
  41. partsect = bytescnt - (bufcnt * buflen);
  42. thisstart = 0;
  43. for(n=0;n<bufcnt;n++) {
  44. thisbuflen = read(fh,buffer,BUFLEN);
  45. if(thisbuflen < 0) {
  46. fprintf(stderr,"Cannot read buffer %d\n",n+1);
  47. return 0;
  48. }
  49. showbytes(thisbuflen,thisstart,buffer);
  50. thisstart += thisbuflen;
  51. if(thisbuflen < BUFLEN) {
  52. partsect = 0;
  53. break;
  54. }
  55. }
  56. if(partsect > 0)
  57. showbytes(partsect,thisstart,buffer);
  58. return 1;
  59. }
  60. void showbytes(int thisbuflen, int thisstart,char *buffer)
  61. {
  62. int thisend = thisstart + thisbuflen;
  63. int m = 0;
  64. char *p = buffer;
  65. char temp1[2000], temp2[2000], temp3[2], temp4[64];
  66. temp1[0] = ENDOFSTR;
  67. temp2[0] = ENDOFSTR;
  68. temp3[1] = ENDOFSTR;
  69. while(m < thisbuflen) {
  70. sprintf(temp4,"%d",*p);
  71. strcat(temp2,temp4);
  72. strcat(temp2," ");
  73. if(isprint(*p))
  74. temp3[0] = *p;
  75. else
  76. temp3[0] = '~';
  77. strcat(temp1,temp3);
  78. strcat(temp1," ");
  79. p++;
  80. m++;
  81. }
  82. fprintf(stdout,"CHARS %d to %d\n",thisstart + 1,thisend);
  83. fprintf(stdout,"%s\n",temp1);
  84. fprintf(stdout,"%s\n",temp2);
  85. fflush(stdout);
  86. }