Skip to content

Instantly share code, notes, and snippets.

@gmmephisto
Last active February 11, 2018 20:07
Show Gist options
  • Save gmmephisto/6ca418982a43aa4af877b96a5c35802b to your computer and use it in GitHub Desktop.
Save gmmephisto/6ca418982a43aa4af877b96a5c35802b to your computer and use it in GitHub Desktop.
show sparse file map
#define _FILE_OFFSET_BITS 64
#define _GNU_SOURCE 1
#include <stdio.h>
#include <stdlib.h>
#include <sys/param.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\n", argv[0]);
}
int fd = open(argv[1], O_RDONLY);
if(fd == -1) {
perror("failed to open the file.");
exit(EXIT_FAILURE);
}
off_t offset = 0;
struct stat status;
fstat(fd, &status);
const off_t size = status.st_size;
do {
off_t data = lseek(fd, offset, SEEK_DATA);
off_t hole = lseek(fd, offset, SEEK_HOLE);
if (data == -1 && hole == -1) {
data = offset;
}
if (data == offset) {
if (hole == -1) {
hole = size;
}
fprintf(stdout, "data: %lld %lld\n",
(unsigned long long)data,
(unsigned long long)hole);
}
if (hole == offset) {
if (data == -1) {
data = size;
}
fprintf(stdout, "hole: %lld %lld\n",
(unsigned long long)hole,
(unsigned long long)data);
}
offset = MAX(data, hole);
} while (offset < size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment