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
|
#include <errno.h> /* for errno */
#include <error.h> /* for error(3gnu) */
#include <fcntl.h> /* for O_RDONLY */
#include <inttypes.h> /* for PRI*, uint*_t, int*_t */
#include <stdbool.h> /* for bool */
#include <stdio.h> /* for printf */
#include <sys/stat.h> /* for open(2), fstat(2) and struct stat */
#include <unistd.h> /* for close(2), read(2), lseek(2), SEEK_SET */
int main(int argc, char *argv[]) {
bool err = false;
for (int i = 1; i < argc; i++) {
const char *filename = argv[i];
int fd = open(filename, O_RDONLY);
if (fd < 0) {
err = true;
error(0, errno, "open %s", filename);
continue;
}
struct stat st;
if (fstat(fd, &st) < 0) {
err = true;
error(0, errno, "fstat %s", filename);
close(fd);
continue;
}
if (lseek(fd, st.st_size/2, SEEK_SET) < 0) {
err = true;
error(0, errno, "lseek %s", filename);
close(fd);
continue;
}
uint8_t b;
int n = read(fd, &b, sizeof(b));
if (n <= 0) {
if (n == 0)
error(0, 0, "read %s: unexpected end of file", filename);
else
error(0, errno, "read %s", filename);
err = true;
close(fd);
continue;
}
printf("%"PRId64":%"PRIx8" %s\n", (int64_t)st.st_size, b, filename);
close(fd);
}
return err ? 1 : 0;
}
|