io: don't truncate, and use pread/pwrite

Signed-off-by: Sean Cross <sean@xobs.io>
This commit is contained in:
Sean Cross 2019-06-12 18:55:15 +08:00
parent aa387e176d
commit a161ce7b8d

View File

@ -10,19 +10,15 @@ struct pang_io {
}; };
ssize_t pang_write(struct pang_io *io, off_t offset, const void *buf, size_t count) { ssize_t pang_write(struct pang_io *io, off_t offset, const void *buf, size_t count) {
if (-1 == lseek(io->fd, offset, SEEK_SET)) return pwrite(io->fd, buf, count, offset);
return -1;
return write(io->fd, buf, count);
} }
ssize_t pang_read(struct pang_io *io, off_t offset, void *buf, size_t count) { ssize_t pang_read(struct pang_io *io, off_t offset, void *buf, size_t count) {
if (-1 == lseek(io->fd, offset, SEEK_SET)) return pread(io->fd, buf, count, offset);
return -1;
return read(io->fd, buf, count);
} }
struct pang_io *pang_open(const char *pathname) { struct pang_io *pang_open(const char *pathname) {
int fd = open(pathname, O_RDWR | O_TRUNC | O_CREAT, 0777); int fd = open(pathname, O_RDWR | O_CREAT, 0777);
if (-1 == fd) if (-1 == fd)
return NULL; return NULL;
struct pang_io *io = malloc(sizeof(struct pang_io)); struct pang_io *io = malloc(sizeof(struct pang_io));