#include #include #include #include #include #include #include int main(int argc, char **argv) { int fd; /* File descriptor. */ int len; /* Length of data read from file. */ /* Ensure we have a file to open. */ if (argc < 2) return 1; /* Try to open the file. */ fd = open(argv[1], O_RDONLY, 0); /* Exit if open failed. */ if (fd == -1) return 1; if (argc == 2) { /* Just print out the file length. */ char mesg[16]; int len = lseek(fd, 0, SEEK_END); /* Get the length of the file. */ sprintf(mesg, "%i\n", len); /* Format number as a string. */ write(1, mesg, strlen(mesg)); return 0; } else { /* Read and print out the byte at the specified offset. */ char buf[2]; int offset = atoi(argv[2]); /* Offset from which to read a byte. */ lseek(fd, offset, SEEK_SET); /* Seek to that offset. */ len = read(fd, buf, 1); /* Try to read a byte. */ if (len == 1) { /* Byte read successful. */ buf[1] = '\n'; /* Include a newline when printing out. */ write(1, buf, 2); return 0; } else { /* Byte read failed. */ const char *mesg = "Readn't\n"; write(1, mesg, strlen(mesg)); return 1; } } }