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