Imported Upstream version 2.17
[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, off_t offset)
26 {
27   this->secLength=secLength;
28   this->sectrk=sectrk;
29   this->tracks=tracks;
30   this->offset=offset;
31 }
32 /*}}}*/
33 /* Device_close          -- Close an image file                     */ /*{{{*/
34 const char *Device_close(struct Device *this)
35 {
36   this->opened=0;
37   return ((close(this->fd)==-1)?strerror(errno):(const char*)0);
38 }
39 /*}}}*/
40 /* Device_readSector     -- read a physical sector                  */ /*{{{*/
41 const char *Device_readSector(const struct Device *this, int track, int sector, char *buf)
42 {
43   int res;
44
45   assert(sector>=0);
46   assert(sector<this->sectrk);
47   assert(track>=0);
48   assert(track<this->tracks);
49   if (lseek(this->fd,(off_t)(((sector+track*this->sectrk)*this->secLength)+this->offset),SEEK_SET)==-1) 
50   {
51     return strerror(errno);
52   }
53   if ((res=read(this->fd, buf, this->secLength)) != this->secLength) 
54   {
55     if (res==-1)
56     {
57       return strerror(errno);
58     }
59     else memset(buf+res,0,this->secLength-res); /* hit end of disk image */
60   }
61   return (const char*)0;
62 }
63 /*}}}*/
64 /* Device_writeSector    -- write physical sector                   */ /*{{{*/
65 const char *Device_writeSector(const struct Device *this, int track, int sector, const char *buf)
66 {
67   assert(sector>=0);
68   assert(sector<this->sectrk);
69   assert(track>=0);
70   assert(track<this->tracks);
71   if (lseek(this->fd,(off_t)(((sector+track*this->sectrk)*this->secLength)+this->offset),SEEK_SET)==-1)
72   {
73     return strerror(errno);
74   }
75   if (write(this->fd, buf, this->secLength) == this->secLength) return (const char*)0;
76   return strerror(errno);
77 }
78 /*}}}*/