Created
September 3, 2018 16:20
-
-
Save chrisdone/c6a98656cc1867f5781ef9e4fd6bdbe2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdio.h> | |
| #include <fcntl.h> | |
| #include <unistd.h> | |
| #include <string.h> | |
| #define BUFFER_SIZE 8192 | |
| size_t process_data(char *text, size_t bytes_read) | |
| { | |
| size_t popCount = 0; | |
| while (bytes_read > 0) { | |
| char *ptr = memchr(text, '\n', bytes_read); | |
| if (ptr == NULL) { | |
| return popCount; | |
| } else { | |
| popCount++; | |
| bytes_read = bytes_read - ((ptr - text) + 1); | |
| text = ptr + 1; | |
| } | |
| } | |
| } | |
| int main(int argc, char **argv) | |
| { | |
| if (argc < 2) { | |
| return 1; | |
| } | |
| char *in_filename = argv[1]; | |
| FILE *in_file = fopen(in_filename, "r"); | |
| if (!in_file) { | |
| return 1; | |
| } | |
| char buffer[BUFFER_SIZE]; | |
| size_t total_bytes_read = 0; | |
| size_t bytes_read = fread(buffer, 1, BUFFER_SIZE, in_file); | |
| size_t newline_count = 0; | |
| while (bytes_read > 0) { | |
| total_bytes_read += bytes_read; | |
| newline_count += process_data(buffer, bytes_read); | |
| bytes_read = fread(buffer, 1, BUFFER_SIZE, in_file); | |
| } | |
| printf("%zu\n", newline_count); | |
| fclose(in_file); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment