Created
February 19, 2021 05:08
-
-
Save jiahuif/199d969f932ef544f5326457679a2a96 to your computer and use it in GitHub Desktop.
zerocount.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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