Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
open/read vs open/mmap vs fopen/fread on clang
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
inline int get_fsize(int fd) {
struct stat sb;
int err;
err = fstat(fd, &sb);
if (err) {
fprintf(stderr, "fstat error! [%s]\n", strerror(errno));
return -1;
}
return sb.st_size;
}
int main(int argc, char *argv[]) {
int fd;
char *path, *addr;
int i, cnt = 0, err;
int fsize;
if (argc < 2) {
fprintf(stderr, "require file path.\n");
return -1;
}
path = argv[1];
fd = open(path, O_RDONLY);
fsize = get_fsize(fd);
if (fsize < 0) {
return -1;
}
addr = mmap(NULL, fsize, PROT_READ, MAP_SHARED, fd, 0);
for (i=0; i<fsize; i++) {
if (addr[i] == 0x00) cnt++;
}
err = munmap(addr, fsize);
if (err) {
fprintf(stderr, "munmap error! [%d]\n", err);
}
close(fd);
printf("%s: size=%d cnt=%d\n", path, fsize, cnt);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment