]> git.ozlabs.org Git - ccan/blob - junkcode/codedr@gmail.com-grok/grok.c
opt: add OPT_EARLY and opt_early_parse.
[ccan] / junkcode / codedr@gmail.com-grok / grok.c
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 /**
11  ** grok -- program to a alter bytes at an offset
12  **
13  ** Sometimes it useful to alter bytes in a binary file.
14  ** To those who would 'just use emacs', the binary is not always a file on disk.  
15  **
16  ** codedr@gmail.com
17  **
18  ** License: Public Domain
19  */
20
21 int
22 main(int argc, char **argv)
23 {
24     int i, dc = 0, fd;
25     int sz, cnt, offset;
26     char *fn;
27     unsigned char *buf, *data;
28     /* grok fn offset data */
29
30     if (3 > argc) {
31         fputs("usage: grok fn offset [cdata]+\n", stderr);
32         exit(1);
33     }
34     fn = argv[1];
35     offset = strtol(argv[2], NULL, 16);
36     data = (unsigned char *) calloc(argc - 2, sizeof(unsigned char));
37     for (i = 3; i < argc; i++) {
38         long x;
39         x = strtol(argv[i], NULL, 16);
40         data[dc++] = 0xff & x;
41     }
42
43     if (0 > (fd = open(fn, O_RDWR))) {
44         fprintf(stderr, "cannot open %s, errno %d\n", fn, errno);
45         exit(2);
46     }
47
48     if (0 > lseek(fd, offset, SEEK_SET)) {
49         fprintf(stderr, "cannot seek to %x, errno %d\n", offset, errno);
50         exit(2);
51     }
52
53     buf = (unsigned char *) calloc(dc, sizeof(unsigned char));
54
55     if (0 > (cnt = read(fd, buf, dc))) {
56         fprintf(stderr, "cannot read %d bytes at %x, errno %d\n", 
57             dc, offset, errno);
58         exit(3);
59     }
60     printf("read %d of %d bytes\n", cnt, dc);
61     /* dumpBuf(buf, cnt); */
62
63     if (0 > lseek(fd, offset, SEEK_SET)) {
64         fprintf(stderr, "cannot seek to %x, errno %d\n", offset, errno);
65         exit(2);
66     }
67
68     if (0 > (sz = write(fd, data, cnt))) {
69         fprintf(stderr, "cannot write %d bytes at %x, errno %d\n", 
70             cnt, offset, errno);
71         exit(4);
72     }
73     printf("wrote %d of %d bytes\n", sz, cnt);
74     exit(0);
75 }