wut/libraries/wutdevoptab/devoptab_fs_write.c

69 lines
1.5 KiB
C
Raw Normal View History

#include "devoptab_fs.h"
2018-05-27 12:11:45 +01:00
ssize_t
__wut_fs_write(struct _reent *r,
void *fd,
const char *ptr,
size_t len)
{
FSStatus status = 0;
FSCmdBlock cmd;
uint8_t *alignedWriteBuffer;
uint32_t bytes, bytesWritten;
__wut_fs_file_t *file;
if (!fd || !ptr) {
r->_errno = EINVAL;
return -1;
}
FSInitCmdBlock(&cmd);
file = (__wut_fs_file_t *)fd;
bytesWritten = 0;
2018-05-27 12:11:45 +01:00
// Check that the file was opened with write access
if ((file->flags & O_ACCMODE) == O_RDONLY) {
r->_errno = EBADF;
return -1;
}
// Copy to internal buffer due to alignment requirement and write in chunks.
alignedWriteBuffer = memalign(0x40, 8192);
while (len > 0) {
size_t toWrite = len > 8192 ? 8192 : len;
2018-05-27 12:11:45 +01:00
// Copy to internal buffer
memcpy(alignedWriteBuffer, ptr, toWrite);
2018-05-27 12:11:45 +01:00
// Write the data
status = FSWriteFile(__wut_devoptab_fs_client, &cmd, alignedWriteBuffer,
1, toWrite, file->fd, 0, -1);
if (status <= 0) {
break;
2018-05-27 12:11:45 +01:00
}
bytes = (uint32_t)status;
2018-05-27 12:11:45 +01:00
file->offset += bytes;
bytesWritten += bytes;
ptr += bytes;
len -= bytes;
if (bytes < toWrite) {
break;
}
}
free(alignedWriteBuffer);
// Return partial write
if (bytesWritten > 0) {
return bytesWritten;
}
if (status < 0) {
r->_errno = __wut_fs_translate_error(status);
return -1;
2018-05-27 12:11:45 +01:00
}
return 0;
2018-05-27 12:11:45 +01:00
}