ssn-installer/src/fileReader.c

66 lines
1.7 KiB
C
Raw Normal View History

2018-07-17 17:19:13 +02:00
#include <errno.h>
#include <stdio.h>
2018-07-24 17:07:47 +02:00
#include <stdlib.h>
#include <string.h>
2018-07-17 17:19:13 +02:00
#include "fileReader.h"
2018-07-24 17:07:47 +02:00
#include "fileUtilities.h"
2018-07-17 17:19:13 +02:00
2018-07-24 17:07:47 +02:00
//minimum of two integers
#define min(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
2018-07-17 17:19:13 +02:00
2018-07-24 17:07:47 +02:00
//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);
2018-07-17 17:19:13 +02:00
}
2018-07-24 17:07:47 +02:00
//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;
2018-07-17 17:19:13 +02:00
}
2018-07-24 17:07:47 +02:00
//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;
2018-07-17 17:19:13 +02:00
}