#include #include #include #include #include "fileReader.h" #include "fileUtilities.h" //minimum of two integers #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) //Opens the given file at the given offset void initFileReader(char path[], unsigned long offset) { file.name = path; file.filePointer = fopen(file.name, "r"); if (file.filePointer == NULL) { fprintf(stderr, "Could not open file %s for reading: %s\n", file.name, strerror(errno)); exit(1); } //get file size fseek(file.filePointer, 0L, SEEK_END); file.size = ftell(file.filePointer); //seek to offset if (offset != 0UL) { fseek(file.filePointer, offset, SEEK_SET); } else { rewind(file.filePointer); } file.offset = offset; } //Reads the given amount of bytes from the file and returns them. Automatically opens next file if EOF is reached. char* getBytes(unsigned long numBytes) { char* output = malloc(numBytes); if (output == NULL) { fprintf(stderr, "Could not allocate %lu bytes.\n", numBytes); exit(1); } char* bufferPosition = output; unsigned long remainingBytes = numBytes; //As long as we still need to read bytes while (remainingBytes > 0) { //Read as many bytes as we can from the current file const unsigned long availableBytes = min(remainingBytes, file.size - file.offset); readBytesIntoBuffer(bufferPosition, availableBytes); bufferPosition += availableBytes; remainingBytes -= availableBytes; //If we've reached end of file, close file and open next file if (file.offset == file.size) { openNextFile(); } } return output; }