76 lines
1.4 KiB
C
76 lines
1.4 KiB
C
#include "file.h"
|
|
|
|
#include <errno.h>
|
|
#include <stdio.h>
|
|
|
|
// Up to 256 files can be open
|
|
FILE *files[256];
|
|
|
|
int openFile(int fd, const char *path, const char *mode) {
|
|
if (files[fd] != NULL) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
files[fd] = fopen(path, mode);
|
|
if (files[fd] == NULL) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
return STATUS_READY;
|
|
}
|
|
|
|
int closeFile(int fd) {
|
|
FILE *f = files[fd];
|
|
|
|
if (f == NULL) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
int ret = fclose(files[fd]);
|
|
if (ret != 0) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
files[fd] = NULL;
|
|
|
|
return STATUS_READY;
|
|
}
|
|
|
|
int readByte(const int fd, uint8_t *data) {
|
|
if (files[fd] == NULL) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
int status = 0;
|
|
int count = fread(data, 1, 1, files[fd]);
|
|
// Error or EOF
|
|
if (count != 1) {
|
|
int error = ferror(files[fd]);
|
|
int eof = feof(files[fd]);
|
|
if (error != 0) {
|
|
status = STATUS_ERROR;
|
|
} else if (eof != 0) {
|
|
status = STATUS_EOF;
|
|
}
|
|
}
|
|
|
|
return STATUS_READY | status;
|
|
}
|
|
|
|
int writeByte(const int fd, const uint8_t data) {
|
|
if (files[fd] == NULL) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
int status = 0;
|
|
int count = fwrite(&data, 1, 1, files[fd]);
|
|
// Error or EOF
|
|
if (count != 1 && ferror(files[fd]) != 0) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
if (fflush(files[fd]) != 0) {
|
|
return STATUS_READY | STATUS_ERROR;
|
|
}
|
|
|
|
return STATUS_READY | status;
|
|
} |