177eed0b0b757749adcc17bcc92eb767536e458e markd Fri Jan 10 10:13:42 2020 -0800 added mustSeek function diff --git src/lib/common.c src/lib/common.c index 15a1da2..17d09da 100644 --- src/lib/common.c +++ src/lib/common.c @@ -2719,30 +2719,47 @@ return x; } void mustGetLine(FILE *file, char *buf, int charCount) /* Read at most charCount-1 bytes from file, but stop after newline if one is * encountered. The string in buf is '\0'-terminated. (See man 3 fgets.) * Die if there is an error. */ { char *success = fgets(buf, charCount, file); if (success == NULL && charCount > 0) buf[0] = '\0'; if (ferror(file)) errAbort("mustGetLine: fgets failed: %s", strerror(ferror(file))); } + +static char *getWhenceStr(int whence) +/* get string description of fseek/lseek whence parameter */ +{ +return ((whence == SEEK_SET) ? "SEEK_SET" : (whence == SEEK_CUR) ? "SEEK_CUR" : + (whence == SEEK_END) ? "SEEK_END" : "invalid 'whence' value"); + +} + +void mustSeek(FILE *file, off_t offset, int whence) +/* Seek to given offset, relative to whence (see man fseek) in file or errAbort. */ +{ +int ret = fseek(file, offset, whence); +if (ret < 0) + errnoAbort("fseek(%lld, %s (%d)) failed", (long long)offset, getWhenceStr(whence), whence); +} + int mustOpenFd(char *fileName, int flags) /* Open a file descriptor (see man 2 open) or squawk and die. */ { if (sameString(fileName, "stdin")) return STDIN_FILENO; if (sameString(fileName, "stdout")) return STDOUT_FILENO; // mode is necessary when O_CREAT is given, ignored otherwise int mode = 0666; int fd = open(fileName, flags, mode); if (fd < 0) { char *modeName = ""; if ((flags & (O_WRONLY | O_CREAT | O_TRUNC)) == (O_WRONLY | O_CREAT | O_TRUNC)) modeName = " to create and truncate"; @@ -2785,33 +2802,31 @@ { if (result < 0) errnoAbort("mustWriteFd: write failed"); else errAbort("mustWriteFd only wrote %lld of %lld bytes. Likely the disk is full.", (long long)result, (long long)size); } } off_t mustLseek(int fd, off_t offset, int whence) /* Seek to given offset, relative to whence (see man lseek) in file descriptor fd or errAbort. * Return final offset (e.g. if this is just an (fd, 0, SEEK_CUR) query for current position). */ { off_t ret = lseek(fd, offset, whence); if (ret < 0) - errnoAbort("lseek(%d, %lld, %s (%d)) failed", fd, (long long)offset, - ((whence == SEEK_SET) ? "SEEK_SET" : (whence == SEEK_CUR) ? "SEEK_CUR" : - (whence == SEEK_END) ? "SEEK_END" : "invalid 'whence' value"), whence); + errnoAbort("lseek(%d, %lld, %s (%d)) failed", fd, (long long)offset, getWhenceStr(whence), whence); return ret; } void mustCloseFd(int *pFd) /* Close file descriptor *pFd if >= 0, abort if there's an error, set *pFd = -1. */ { if (pFd != NULL && *pFd >= 0) { if (close(*pFd) < 0) errnoAbort("close failed"); *pFd = -1; } } char *addSuffix(char *head, char *suffix)