dj(1): refactor Io_fdseek

This commit is contained in:
dtb 2024-06-26 12:40:36 -06:00
parent 45a880455d
commit 66f5498232
Signed by: trinity
GPG Key ID: 34C0543BBB6AF81B

View File

@ -156,18 +156,15 @@ Io_fdopen(struct Io *io, char *fn){
return fd; return fd;
} }
/* Seeks io->seek bytes through *io's file descriptor, (counter-intuitively) /* Seeks io->seek bytes through *io's file descriptor, subtracting the number
* returning -1 if successful and a sysexits.h exit code if an unrecoverable * of sought bytes from io->seek. This procedure leaves garbage in io->buf. */
* error occurred. io->buf will be cleared of useful bytes and io->seek will static void
* be set to zero to indicate the seek occurred. */
static int
Io_fdseek(struct Io *io){ Io_fdseek(struct Io *io){
int (*op)(int, void *, size_t);
if(!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1) if(io->seek != 0
return -1; || (!fdisstd(io->fd) && lseek(io->fd, io->seek, SEEK_SET) != -1))
return;
/* repeated code to get the condition out of the loop */
if(io->fl == write_flags){ if(io->fl == write_flags){
memset(io->buf, '\0', io->bs); memset(io->buf, '\0', io->bs);
/* We're going to cheat and use bufuse as the retval for write(2), /* We're going to cheat and use bufuse as the retval for write(2),
@ -186,12 +183,11 @@ Io_fdseek(struct Io *io){
/* second chance */ /* second chance */
io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek)); io->bufuse = read(io->fd, io->buf, MIN(io->bs, io->seek));
}while((io->seek -= io->bufuse) > 0 && io->bufuse != 0); }while((io->seek -= io->bufuse) > 0 && io->bufuse != 0);
}else }
return EX_SOFTWARE;
io->bufuse = 0; io->bufuse = 0;
return -1; return;
} }
/* Reads io->bs bytes from *io's file descriptor into io->buf, storing the /* Reads io->bs bytes from *io's file descriptor into io->buf, storing the
@ -352,11 +348,10 @@ int main(int argc, char *argv[]){
terminate(ep); terminate(ep);
return EX_OSERR; return EX_OSERR;
}else if(ep[i].seek > 0) }else if(ep[i].seek > 0)
switch(Io_fdseek(&ep[i])){ Io_fdseek(&ep[i]);
case EX_OK: if(ep[i].seek > 0){
output(ep, fmt_output);
terminate(ep); terminate(ep);
return EX_OK; return oserr(ep[i].fn);
} }
} }