|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define readBits(start,size,data) ((*((uint64_t *) &data[(start) / 8]) >> ((start) & 7)) & ((1 << (size)) - 1))
uint64_t readData(const char* filename, unsigned int offset, unsigned int size) {
uint64_t data = 0;
int fd = open(filename, O_RDONLY);
if(fd == -1) {
return data;
}
if(lseek(fd, offset/8, SEEK_SET) == -1) {
close(fd);
return data;
}
ssize_t numBytes = read(fd, &data, sizeof(data));
if(numBytes != sizeof(data)) {
close(fd);
return data;
}
uint64_t* dataPtr = &data;
uint64_t aux = readBits(offset % 8, size, dataPtr);
data = aux;
close(fd);
return data;
}
int main(int argc, char** argv) {
char c;
const char* filename = NULL;
unsigned int offset = 0;
unsigned int size = 0;
while ((c = getopt (argc, argv, "f:o:s:")) != -1) {
switch(c) {
case 'f':
filename = optarg;
break;
case 'o':
offset = atoi(optarg);
break;
case 's':
size = atoi(optarg);
break;
case '?':
return 1;
}
}
if(!filename || !offset || !size) {
fprintf(stderr, "Need to specify filename (-f), offset (-o) and size (-s)\n");
return 1;
}
uint64_t data = readData(filename, offset, size);
printf("Read: 0x%016llX (%llu)\n", data, data);
return 0;
}
|