grok.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <errno.h>
  9. /**
  10. ** grok -- program to a alter bytes at an offset
  11. **
  12. ** Sometimes it useful to alter bytes in a binary file.
  13. ** To those who would 'just use emacs', the binary is not always a file on disk.
  14. **
  15. ** codedr@gmail.com
  16. **
  17. ** Licence: Public Domain
  18. */
  19. int
  20. main(int argc, char **argv)
  21. {
  22. int i, dc = 0, fd;
  23. int sz, cnt, offset;
  24. char *fn;
  25. unsigned char *buf, *data;
  26. /* grok fn offset data */
  27. if (3 > argc) {
  28. fputs("usage: grok fn offset [cdata]+\n", stderr);
  29. exit(1);
  30. }
  31. fn = argv[1];
  32. offset = strtol(argv[2], NULL, 16);
  33. data = (unsigned char *) calloc(argc - 2, sizeof(unsigned char));
  34. for (i = 3; i < argc; i++) {
  35. long x;
  36. x = strtol(argv[i], NULL, 16);
  37. data[dc++] = 0xff & x;
  38. }
  39. if (0 > (fd = open(fn, O_RDWR))) {
  40. fprintf(stderr, "cannot open %s, errno %d\n", fn, errno);
  41. exit(2);
  42. }
  43. if (0 > lseek(fd, offset, SEEK_SET)) {
  44. fprintf(stderr, "cannot seek to %x, errno %d\n", offset, errno);
  45. exit(2);
  46. }
  47. buf = (unsigned char *) calloc(dc, sizeof(unsigned char));
  48. if (0 > (cnt = read(fd, buf, dc))) {
  49. fprintf(stderr, "cannot read %d bytes at %x, errno %d\n",
  50. dc, offset, errno);
  51. exit(3);
  52. }
  53. printf("read %d of %d bytes\n", cnt, dc);
  54. /* dumpBuf(buf, cnt); */
  55. if (0 > lseek(fd, offset, SEEK_SET)) {
  56. fprintf(stderr, "cannot seek to %x, errno %d\n", offset, errno);
  57. exit(2);
  58. }
  59. if (0 > (sz = write(fd, data, cnt))) {
  60. fprintf(stderr, "cannot write %d bytes at %x, errno %d\n",
  61. cnt, offset, errno);
  62. exit(4);
  63. }
  64. printf("wrote %d of %d bytes\n", sz, cnt);
  65. exit(0);
  66. }