Advertisement
Guest User

Untitled

a guest
Mar 8th, 2013
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <vector>
  5.  
  6. inline void on_line(char *p, size_t size) {
  7.     ///....
  8. }
  9.  
  10. int main() {
  11.     FILE *file = stdin;
  12.  
  13.     const size_t buf_size = 4096*4;
  14.     size_t n = buf_size;
  15.     char buf[buf_size + 1]; //+1 for fake '/n'
  16.     std::vector<char> dynamic_line; //for lines, which spans buffer
  17.  
  18.     size_t i, j;
  19.     i = n;
  20.     j = n;
  21.     buf[n] = '\n';
  22.     bool use_dynamic_buffer = false;
  23.     while (1) {
  24.         assert(buf[n] == '\n'); //this assert makes code faster, LOL
  25.         //volatile char p = buf[n];
  26.         while (buf[i] != '\n') {
  27.             ++i;
  28.         }
  29.         if (i < n) {
  30.             assert(buf[i] == '\n');
  31.             if (!use_dynamic_buffer) {
  32.                 on_line(buf + j, i - j);
  33.             } else {
  34.                 assert(j == 0);
  35.                 dynamic_line.insert(dynamic_line.end(), buf, buf + i);
  36.                 on_line(&*dynamic_line.begin(), dynamic_line.size());
  37.                 dynamic_line.resize(0);
  38.                 use_dynamic_buffer = false;
  39.             }
  40.             ++i;
  41.             j = i;
  42.         } else {
  43.             if (i > j) {
  44.                 dynamic_line.insert(dynamic_line.end(), buf + j, buf + i);
  45.                 use_dynamic_buffer = true;
  46.             }
  47.             j = 0;
  48.             i = 0;
  49.             if (n < buf_size) { //previos fread was last
  50.                 break;
  51.             }
  52.             n = fread(buf, 1, buf_size, file);
  53.             buf[n] = '\n';
  54.         }
  55.     }
  56.     if (!use_dynamic_buffer) { //special code for last line without EOL (common corner case for hand-made text files)
  57.         if (i > j)
  58.             on_line(buf + j, i - j);
  59.     } else {
  60.         dynamic_line.insert(dynamic_line.end(), buf + j, buf + i);
  61.         if (dynamic_line.size())
  62.             on_line(&*dynamic_line.begin(), dynamic_line.size());
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement