/** * \file * * * \brief KFile interface implementation in Posix systems. * * \author Luca Ottaviano */ #include #include static size_t kfile_posix_read(struct KFile *_fd, void *buf, size_t size) { KFilePosix *fd = KFILEPOSIX_CAST(_fd); size_t len = fread(buf, sizeof(uint8_t), size, fd->fp); fd->fd.seek_pos += len; return len; } static size_t kfile_posix_write(struct KFile *_fd, const void *buf, size_t size) { KFilePosix *fd = KFILEPOSIX_CAST(_fd); size_t len = fwrite(buf, sizeof(uint8_t), size, fd->fp); fd->fd.seek_pos += len; fd->fd.size = MAX(fd->fd.size, fd->fd.seek_pos); return len; } static kfile_off_t kfile_posix_seek(struct KFile *_fd, kfile_off_t offset, KSeekMode whence) { KFilePosix *fd = KFILEPOSIX_CAST(_fd); int std_whence; switch (whence) { case KSM_SEEK_CUR: std_whence = SEEK_CUR; break; case KSM_SEEK_END: std_whence = SEEK_END; break; case KSM_SEEK_SET: std_whence = SEEK_SET; break; default: ASSERT(0); return EOF; } int err = fseek(fd->fp, offset, std_whence); if (err) return err; fd->fd.seek_pos = ftell(fd->fp); return fd->fd.seek_pos; } static int kfile_posix_close(struct KFile *_fd) { KFilePosix *fd = KFILEPOSIX_CAST(_fd); return fclose(fd->fp); } static int kfile_posix_flush(struct KFile *_fd) { KFilePosix *fd = KFILEPOSIX_CAST(_fd); return fflush(fd->fp); } FILE *kfile_posix_init(KFilePosix *file, const char *filename, const char *mode) { memset(file, 0, sizeof(*file)); DB(file->fd._type = KFT_KFILEPOSIX); file->fd.read = kfile_posix_read; file->fd.write = kfile_posix_write; file->fd.close = kfile_posix_close; file->fd.seek = kfile_posix_seek; file->fd.flush = kfile_posix_flush; file->fp = fopen(filename, mode); fseek(file->fp, 0, SEEK_END); file->fd.size = ftell(file->fp); fseek(file->fp, 0, SEEK_SET); return file->fp; }