Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kazuho
Forked from ryochack/open_read.c
Last active June 6, 2017 10:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazuho/6916598 to your computer and use it in GitHub Desktop.
Save kazuho/6916598 to your computer and use it in GitHub Desktop.
#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;
char buf[65536];
int i, cnt = 0;
int offset, chunk_size, 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;
}
offset = 0;
while (offset != fsize) {
chunk_size = fsize - offset;
if (chunk_size > sizeof(buf))
chunk_size = sizeof(buf);
length = read(fd, buf, chunk_size);
if (length != chunk_size) {
fprintf(stderr, "read error! [%d]\n", length);
break;
}
for (i=0; i<length; i++) {
if (buf[i] == 0x00) cnt++;
}
offset += chunk_size;
}
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