61 lines
1.7 KiB
C
61 lines
1.7 KiB
C
#include "io.h"
|
|
#include "common.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
file_t* file_open(const char* filename, const char* mode, size_t page_size)
|
|
{
|
|
FILE* handle = fopen(filename, mode);
|
|
|
|
if (!handle) {
|
|
printfv(VERBOSITY_NORMAL, "Can't open file %s.\n", filename);
|
|
return NULL;
|
|
}
|
|
|
|
printfv(VERBOSITY_DEBUG, "File %s opened in %s with page size %zu.\n", filename, mode, page_size);
|
|
file_t* result = malloc(sizeof(file_t));
|
|
|
|
result->page_size = page_size;
|
|
result->file = handle;
|
|
result->filename = malloc(strlen(filename) + 1);
|
|
result->buffer = malloc(page_size);
|
|
|
|
strcpy(result->filename, filename);
|
|
|
|
return result;
|
|
}
|
|
|
|
void file_close(file_t* file)
|
|
{
|
|
printfv(VERBOSITY_DEBUG, "Closing file %s.\n", file->filename);
|
|
fclose(file->file);
|
|
|
|
free(file->filename);
|
|
free(file->buffer);
|
|
free(file);
|
|
}
|
|
|
|
size_t file_read(file_t* file, unsigned block, void* buffer, size_t length)
|
|
{
|
|
memset(file->buffer, 0, file->page_size);
|
|
|
|
printfv(VERBOSITY_DEBUG, "Reading page %u of %s.\n", block, file->filename);
|
|
|
|
fseek(file->file, block * file->page_size, SEEK_SET);
|
|
int read = fread(file->buffer, 1, file->page_size, file->file);
|
|
memcpy(buffer, file->buffer, length);
|
|
return read;
|
|
}
|
|
|
|
size_t file_write(file_t* file, unsigned block, const void* buffer, size_t length)
|
|
{
|
|
memset(file->buffer, 0, file->page_size);
|
|
memcpy(file->buffer, buffer, length);
|
|
|
|
printfv(VERBOSITY_DEBUG, "Writing page %u to %s. (%zu bytes)\n", block, file->filename, length);
|
|
fseek(file->file, block * file->page_size, SEEK_SET);
|
|
return fwrite(file->buffer, 1, file->page_size, file->file);
|
|
}
|