Last active
December 19, 2015 21:29
-
-
Save ryochack/6020414 to your computer and use it in GitHub Desktop.
open/read vs open/mmap vs fopen/fread on clang
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 <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++; | |
} | |
free(buf); | |
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