Create a gist now

Instantly share code, notes, and snippets.

open/read vs open/mmap vs fopen/fread on clang
##include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.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, *buf;
int i, cnt = 0;
int fsize;
int length;
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;
buf = (char*)malloc(fsize);
length = read(fd, buf, fsize);
if (length < fsize) {
fprintf(stderr, "read error! [%d]\n", length);
for (i=0; i<fsize; i++) {
if (buf[i] == 0x00) cnt++;
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