BeRTOS
kfile_posix.c
Go to the documentation of this file.
00001 
00038 #include <emul/kfile_posix.h>
00039 #include <string.h>
00040 
00041 static size_t kfile_posix_read(struct KFile *_fd, void *buf, size_t size)
00042 {
00043     KFilePosix *fd = KFILEPOSIX_CAST(_fd);
00044     size_t len = fread(buf, sizeof(uint8_t), size, fd->fp);
00045     fd->fd.seek_pos += len;
00046     return len;
00047 }
00048 
00049 static size_t kfile_posix_write(struct KFile *_fd, const void *buf, size_t size)
00050 {
00051     KFilePosix *fd = KFILEPOSIX_CAST(_fd);
00052     size_t len = fwrite(buf, sizeof(uint8_t), size, fd->fp);
00053     fd->fd.seek_pos += len;
00054     fd->fd.size = MAX(fd->fd.size, fd->fd.seek_pos);
00055     return len;
00056 }
00057 
00058 static kfile_off_t kfile_posix_seek(struct KFile *_fd, kfile_off_t offset, KSeekMode whence)
00059 {
00060     KFilePosix *fd = KFILEPOSIX_CAST(_fd);
00061     int std_whence;
00062     switch (whence)
00063     {
00064         case KSM_SEEK_CUR:
00065             std_whence = SEEK_CUR;
00066             break;
00067         case KSM_SEEK_END:
00068             std_whence = SEEK_END;
00069             break;
00070         case KSM_SEEK_SET:
00071             std_whence = SEEK_SET;
00072             break;
00073         default:
00074             ASSERT(0);
00075             return EOF;
00076     }
00077     int err = fseek(fd->fp, offset, std_whence);
00078     if (err)
00079         return err;
00080 
00081     fd->fd.seek_pos = ftell(fd->fp);
00082     return fd->fd.seek_pos;
00083 }
00084 
00085 static int kfile_posix_close(struct KFile *_fd)
00086 {
00087     KFilePosix *fd = KFILEPOSIX_CAST(_fd);
00088     return fclose(fd->fp);
00089 }
00090 
00091 static int kfile_posix_flush(struct KFile *_fd)
00092 {
00093     KFilePosix *fd = KFILEPOSIX_CAST(_fd);
00094     return fflush(fd->fp);
00095 }
00096 
00097 FILE *kfile_posix_init(KFilePosix *file, const char *filename, const char *mode)
00098 {
00099     memset(file, 0, sizeof(*file));
00100     DB(file->fd._type = KFT_KFILEPOSIX);
00101     file->fd.read = kfile_posix_read;
00102     file->fd.write = kfile_posix_write;
00103     file->fd.close = kfile_posix_close;
00104     file->fd.seek = kfile_posix_seek;
00105     file->fd.flush = kfile_posix_flush;
00106 
00107     file->fp = fopen(filename, mode);
00108     fseek(file->fp, 0, SEEK_END);
00109     file->fd.size = ftell(file->fp);
00110     fseek(file->fp, 0, SEEK_SET);
00111     return file->fp;
00112 }