title: Reading a text file backwards in C
body: <p>What's the best way to read a file backwards in C? I know at first you may be thinking that this is no use whatsoever, but most logs etc. append the most recent data at the end of the file. I want to read in text from the file backwards, buffering it into lines - that is</p>
  
  <p>abc<br>
  def<br>
  ghi</p>
  
  <p>should read <b>ghi</b>, <b>def</b>, <b>abc</b> in lines.</p>
  
  <p>So far I have tried:</p>
  
  <pre><code>    #include &lt;stdio.h&gt;
      #include &lt;stdlib.h&gt;
  
      void read_file(FILE *fileptr)
      {
          char currentchar = '\0';
          int size = 0;
  
          while( currentchar != '\n' )
          {
              currentchar = fgetc(fileptr); printf("%c\n", currentchar);
              fseek(fileptr, -2, SEEK_CUR);
              if( currentchar == '\n') { fseek(fileptr, -2, SEEK_CUR); break; }
              else size++;
  
          }
          char buffer[size]; fread(buffer, 1, size, fileptr);
          printf("Length: %d chars\n", size);
          printf("Buffer: %s\n", buffer);
  
  
      }
  
  
      int main(int argc, char *argv[])
      {
          if( argc &lt; 2) { printf("Usage: backwards [filename]\n"); return 1; }
  
          FILE *fileptr = fopen(argv[1], "rb");
          if( fileptr == NULL ) { perror("Error:"); return 1; }
  
          fseek(fileptr, -1, SEEK_END); /* Seek to END of the file just before EOF */
          read_file(fileptr);
  
  
          return 0;
  
  
      }
  </code></pre>
  
  <p>In an attempt to simply read one line and buffer it. Sorry that my code is terrible, I am getting so very confused. I know that you would normally allocate memory for the whole file and then read in the data, but for large files that constantly change I thought it would be better to read directly (especially if I want to search for text in a file).</p>
  
  <p>Thanks in advance</p>
  
  <p><strong>* Sorry forgot to mention this will be used on Linux, so newlines are just NL without CR. *</strong></p>