Skip to content

Instantly share code, notes, and snippets.

@jiahuif
Created February 19, 2021 05:08
Show Gist options
  • Save jiahuif/199d969f932ef544f5326457679a2a96 to your computer and use it in GitHub Desktop.
Save jiahuif/199d969f932ef544f5326457679a2a96 to your computer and use it in GitHub Desktop.
zerocount.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s FILE\n", argv[0]);
return 1;
}
int fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}
struct stat s;
if (fstat(fd, &s) < 0) {
perror("stat");
return 1;
}
size_t size = s.st_size;
const char *map = mmap(0, size, PROT_READ, MAP_PRIVATE, fd, 0);
if (map == MAP_FAILED) {
perror("mmap");
return 1;
}
long long zero_cnt = 0, cnt = 0;
for (size_t i = 0; i < size; ++i) {
cnt++;
if (!map[i]) {
zero_cnt++;
}
}
printf("total bytes: %lld, zero bytes: %lld\n", cnt, zero_cnt);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment