Skip to content

Instantly share code, notes, and snippets.

@ryochack
Last active December 19, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryochack/6020421 to your computer and use it in GitHub Desktop.
Save ryochack/6020421 to your computer and use it in GitHub Desktop.
open/read vs open/mmap vs open/bufio.read on golang.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
inline int get_fsize(const char *path) {
struct stat sb;
int err;
err = stat(path, &sb);
if (err) {
fprintf(stderr, "fstat error! [%s]\n", strerror(errno));
return -1;
}
return sb.st_size;
}
int main(int argc, char *argv[]) {
FILE *fp;
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];
fsize = get_fsize(path);
if (fsize < 0) {
return -1;
}
buf = (char*)malloc(fsize);
fp = fopen(path, "r");
length = fread(buf, 1, fsize, fp);
if (length < fsize) {
fprintf(stderr, "fread error! [%d]\n", length);
}
for (i=0; i<fsize; i++) {
if (buf[i] == 0x00) cnt++;
}
free(buf);
fclose(fp);
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