New upstream version 2.20
[debian/cpmtools] / device_posix.c
1 /* #includes */ /*{{{C}}}*//*{{{*/
2 #include "config.h"
3
4 #include <assert.h>
5 #include <errno.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9
10 #include "device.h"
11
12 #ifdef USE_DMALLOC
13 #include <dmalloc.h>
14 #endif
15 /*}}}*/
16
17 /* Device_open           -- Open an image file                      */ /*{{{*/
18 const char *Device_open(struct Device *this, const char *filename, int mode, const char *deviceOpts)
19 {
20   this->fd=open(filename,mode);
21   this->opened=(this->fd==-1?0:1);
22   return ((this->fd==-1)?strerror(errno):(const char*)0);
23 }
24 /*}}}*/
25 /* Device_setGeometry    -- Set disk geometry                       */ /*{{{*/
26 const char *Device_setGeometry(struct Device *this, int secLength, int sectrk, int tracks, off_t offset, const char *libdskGeometry)
27 {
28   this->secLength=secLength;
29   this->sectrk=sectrk;
30   this->tracks=tracks;
31   this->offset=offset;
32   return NULL;
33 }
34 /*}}}*/
35 /* Device_close          -- Close an image file                     */ /*{{{*/
36 const char *Device_close(struct Device *this)
37 {
38   this->opened=0;
39   return ((close(this->fd)==-1)?strerror(errno):(const char*)0);
40 }
41 /*}}}*/
42 /* Device_readSector     -- read a physical sector                  */ /*{{{*/
43 const char *Device_readSector(const struct Device *this, int track, int sector, char *buf)
44 {
45   int res;
46
47   assert(this);
48   assert(sector>=0);
49   assert(sector<this->sectrk);
50   assert(track>=0);
51   assert(track<this->tracks);
52   assert(buf);
53   if (lseek(this->fd,(off_t)(((sector+track*this->sectrk)*this->secLength)+this->offset),SEEK_SET)==-1) 
54   {
55     return strerror(errno);
56   }
57   if ((res=read(this->fd, buf, this->secLength)) != this->secLength) 
58   {
59     if (res==-1)
60     {
61       return strerror(errno);
62     }
63     else memset(buf+res,0,this->secLength-res); /* hit end of disk image */
64   }
65   return (const char*)0;
66 }
67 /*}}}*/
68 /* Device_writeSector    -- write physical sector                   */ /*{{{*/
69 const char *Device_writeSector(const struct Device *this, int track, int sector, const char *buf)
70 {
71   assert(sector>=0);
72   assert(sector<this->sectrk);
73   assert(track>=0);
74   assert(track<this->tracks);
75   if (lseek(this->fd,(off_t)(((sector+track*this->sectrk)*this->secLength)+this->offset),SEEK_SET)==-1)
76   {
77     return strerror(errno);
78   }
79   if (write(this->fd, buf, this->secLength) == this->secLength) return (const char*)0;
80   return strerror(errno);
81 }
82 /*}}}*/