#include #include #include #include #include #include #include #include #include // Define our functions.. unsigned long fileSize(int); int readBinary(int, char *, unsigned long); int main(int, char **); int main(int argc, char **argv) { int fd, i; unsigned long sz; char data[16]; if ((fd = open("alsample.bin", O_RDONLY)) < 1) { fprintf(stderr, "Cannot open alsample.bin: %s\n", strerror(errno)); exit(1); } sz = fileSize(fd); while((i = readBinary(fd, data, sz))) { printf("read %d bytes\n", i); sz =- i; } exit(0); } // Unsigned long to allow for larger file size.. // Hopefully we won't be given a file more than 2 gigabytes in size.. unsigned long fileSize(int fd) { unsigned long sz = 0; char c; while(read(fd, &c, 1)) { sz++; } lseek(fd, SEEK_SET, 0); // Return to beginning of file. return(sz); } int readBinary(int fd, char *data, unsigned long sz) { #ifdef ONE_BYTE_AT_A_TIME // Reading one byte at a time is slow, but since you want // it that way, here is the code to do it. int i; for (i=0; i<16; i++,data++) { if (read(fd, data, 1) != 1) break; } return(i); #else // Much faster way to do it. return(read(fd, data, 16)); #endif }