Skip to content

Instantly share code, notes, and snippets.

@ugudango
Created April 7, 2021 06:48
Show Gist options
  • Save ugudango/b21a379ccabcb7aa1006919d741f6742 to your computer and use it in GitHub Desktop.
Save ugudango/b21a379ccabcb7aa1006919d741f6742 to your computer and use it in GitHub Desktop.
Unix File Reading using Chunking
#define CHUNK_SIZE 256
char char_at(int fd, long long at, enum Direction D) {
static int FD;
static long long left, right;
static char CHUNK[CHUNK_SIZE];
// If outside the file, stop this function.
long long min = lseek(fd, 0, SEEK_SET), max = lseek(fd, 0, SEEK_END);
if (at < min || at >= max) return -1;
// If new file is present, do some resets.
if (FD != fd) goto CHUNK_SETTING;
if (at >= left && at < right) {
return CHUNK[at - left];
} else {
CHUNK_SETTING:
lseek(fd, at, SEEK_SET);
switch (D) {
case AHEAD:
left = at;
right = left + read(fd, CHUNK, CHUNK_SIZE);
return CHUNK[0];
case BEHIND:
// If reading behind from current point would go outside the file, simply read from start.
if (at + 1 < CHUNK_SIZE) {
lseek(fd, 0, SEEK_SET);
read(fd, CHUNK, CHUNK_SIZE);
left = 0;
right = CHUNK_SIZE;
return CHUNK[at];
} else {
lseek(fd, -(CHUNK_SIZE - 1), SEEK_CUR);
read(fd, CHUNK, CHUNK_SIZE);
left = at - (CHUNK_SIZE - 1);
right = left + CHUNK_SIZE;
return CHUNK[CHUNK_SIZE - 1];
}
default:
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment