Skip to content

Instantly share code, notes, and snippets.

@gmmephisto
Last active February 11, 2018 19:01
Show Gist options
  • Save gmmephisto/f2aac5f4620f9654c0b55c382f04db9f to your computer and use it in GitHub Desktop.
Save gmmephisto/f2aac5f4620f9654c0b55c382f04db9f to your computer and use it in GitHub Desktop.
lseek sparse files
#define _FILE_OFFSET_BITS 64
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#ifndef SEEK_DATA
#warning "SEEK_DATA is undeclared and manually defined."
#define SEEK_DATA 3 /* seek to the next data */
#endif
#ifndef SEEK_HOLE
#warning "SEEK_HOLE is undeclared and manually defined."
#define SEEK_HOLE 4 /* seek to the next hole */
#endif
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s file [offset:0] [whence:3]\n", argv[0]);
exit(EXIT_FAILURE);
}
int fd = open(argv[1], O_RDONLY);
if(fd == -1) {
perror("failed to open the file.");
exit(EXIT_FAILURE);
}
off_t offset = 0;
if (argc >= 3) {
offset = atoi(argv[2]);
}
int whence = SEEK_DATA;
if (argc >= 4) {
whence = atoi(argv[3]);
}
off_t result = lseek(fd, offset, whence);
fprintf(stdout, "%lld\n", (unsigned long long)result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment