Skip to content

Instantly share code, notes, and snippets.

@chris3k
Created October 18, 2016 21:57
Show Gist options
  • Save chris3k/049bf1bf23bd3dd1b9cbc438ebafa0d3 to your computer and use it in GitHub Desktop.
Save chris3k/049bf1bf23bd3dd1b9cbc438ebafa0d3 to your computer and use it in GitHub Desktop.
word count c++
#include <algorithm>
#include <fcntl.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
constexpr int BUFFER_SIZE = 1024 * 1024;
size_t line_count(const char *filename) {
int fd = open(filename, O_RDONLY);
if (fd == -1) {
cout << filename << ": " << strerror(errno) << endl;
return -1;
}
posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
char buf[BUFFER_SIZE + 1];
size_t lines = 0;
while (ssize_t rb = read(fd, buf, BUFFER_SIZE)) {
if (rb == -1) {
cout << filename << ": " << strerror(errno) << endl;
close(fd);
return 0;
}
if (!rb) {
break;
}
// lines += std::count(buf, buf+rb, '\n');
for (char *p = buf; (p = (char *)memchr(p, '\n', (buf + rb) - p)); p++)
lines++;
}
close(fd);
return lines;
}
int main(int argc, char const *argv[]) {
// ios_base::sync_with_stdio(0);
for (int i = 1; i < argc; i++) {
cout << " " << line_count(argv[i]) << " " << argv[i] << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment