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