fatcopy/diskio.c
2022-12-23 09:24:19 -05:00

109 lines
2.2 KiB
C

#include "ff.h"
#include "diskio.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
static DSTATUS stat = STA_NOINIT;
static FILE *image = NULL;
static char *imagefile = NULL;
void set_image_filename(char* file) {
if (imagefile) {
free(imagefile);
imagefile = NULL;
}
imagefile = strdup(file);
if (!imagefile) {
fprintf(stderr, "failed to allocate memory for image filename\n");
exit(EXIT_FAILURE);
}
}
DSTATUS disk_status ( BYTE drv )
{
if (drv) return STA_NOINIT;
return stat;
}
DSTATUS disk_initialize ( BYTE drv )
{
if (drv) return RES_NOTRDY;
if (image) {
fprintf(stderr, "Disk was already initialized\n");
return RES_PARERR;
}
if (!imagefile) {
fprintf(stderr, "Must set imagefile before initializing disk\n");
return RES_PARERR;
}
image = fopen(imagefile, "rb+");
if (!image) {
fprintf(stderr, "Couldn't open image file %s\n", imagefile);
return RES_ERROR;
}
stat = 0;
return RES_OK;
}
DRESULT disk_read ( BYTE drv, BYTE *buff, LBA_t sector, UINT count )
{
if (drv) return RES_NOTRDY;
if (fseek(image, sector * 512, SEEK_SET) < 0) {
fprintf(stderr, "fseek failed due to %s\n", strerror(errno));
return RES_ERROR;
}
if (fread(buff, 512, 1, image) != 1) {
fprintf(stderr, "fread failed due to %s\n", strerror(errno));
return RES_ERROR;
}
return RES_OK;
}
DRESULT disk_write ( BYTE drv, const BYTE *buff, LBA_t sector, UINT count )
{
if (drv) return RES_NOTRDY;
if (fseek(image, sector * 512, SEEK_SET) < 0) {
fprintf(stderr, "fseek failed due to %s\n", strerror(errno));
return RES_ERROR;
}
if (fwrite(buff, 512, count, image) < count) {
fprintf(stderr, "fwrite failed due to %s\n", strerror(errno));
return RES_ERROR;
}
return RES_OK;
}
DRESULT disk_ioctl ( BYTE drv, BYTE ctrl, void *buff )
{
DRESULT res = RES_ERROR;
switch (ctrl) {
case CTRL_SYNC :
res = RES_OK;
break;
case GET_BLOCK_SIZE :
*(DWORD*)buff = 1;
res = RES_OK;
break;
default:
res = RES_PARERR;
}
return res;
}