#include #include #include #include #include "errorAndExit.h" #include "fileReader.h" #include "utils/fileUtilities.h" #include "utils/min.h" //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)); errorAndExit(); } //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 writes them into the given buffer. Automatically opens next file if EOF is reached. void getBytes(uint8_t* buffer, unsigned long numBytes, bool isLast) { uint8_t* bufferPosition = buffer; 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); //Read bytes into buffer if we have a valid buffer, otherwise skip bytes if (buffer) { readBytesIntoBuffer(bufferPosition, availableBytes); bufferPosition += availableBytes; } else { skipBytes(availableBytes); } remainingBytes -= availableBytes; //If we've reached end of file, close file and open next file if (file.offset == file.size) { closeCurrentFile(); //Unless we've reached the end, in that case don't open next file in case we've reached the end of the last disk if (!isLast) { openNextFile(); } else if (remainingBytes > 0) { fprintf(stderr, "Reached end of last disk but have to read %lu more bytes.\n", remainingBytes); errorAndExit(); } } } }