Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fcntl.h>
- #include <iostream>
- #include <unistd.h>
- bool IsSpace(char c) {
- return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f';
- }
- int main(int argc, const char* argv[]) {
- if (argc < 2) {
- return 1;
- }
- std::ios::sync_with_stdio(false);
- size_t num_chars = 0;
- size_t num_words = 0;
- size_t num_lines = 0;
- bool prev_space = true;
- bool prev_newline = true;
- int fd = open(argv[1], O_RDONLY);
- if (fd == -1) {
- return 1;
- }
- char buffer[4 << 10];
- ssize_t size = 4 << 10;
- while (size) {
- size = read(fd, buffer, 4 << 10);
- if (size == -1) {
- return 1;
- }
- for (const char* it = buffer; it < buffer + size; ++it) {
- char c = *it;
- ++num_chars;
- if (IsSpace(c)) {
- prev_space = true;
- } else {
- num_words += prev_space;
- prev_space = false;
- }
- if (c == '\n') {
- prev_newline = true;
- } else {
- num_lines += prev_newline;
- prev_newline = false;
- }
- }
- }
- close(fd);
- std::cout
- << num_lines << ' ' << num_words << ' ' << num_chars << ' '
- << argv[1] << std::endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement