title: fread dropping carriage returns in C?
body: <p>I want to be able to read in a Windows text file, modify it in memory, and then overwrite the old file with the modified data. However, fread doesn't seem to store the carriage returns present in my Windows text file, which is throwing things off when I write over the old data. I can't find anyone else who seems to have had this issue.</p>
  
  <p>Here is some example code that demonstrates the problem:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main()
  {
      FILE* textFile;
      long fileSize;
      char fileCharacterBuffer[100];
  
      int i;
      for(i = 0; i &lt; 100; i++)
      {
          fileCharacterBuffer[i] = '\0';
      }
  
      textFile = fopen("./Test.txt", "r+");
  
      fseek(textFile, 0L, SEEK_END);
      fileSize = ftell(textFile);
      fseek(textFile, 0L, SEEK_SET);
  
      fread(fileCharacterBuffer, 1, fileSize, textFile);
  }
  </code></pre>
  
  <p>The test file:</p>
  
  <pre><code>3
  112
  REd
  110
  green
  
  #5/09/2014
  5087 - 5/6/2014
  </code></pre>
  
  <p>Its hex dump, which shows its EOLs are \r\n:</p>
  
  <pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
  
  00000000  33 0D 0A 31 31 32 0D 0A 52 45 64 0D 0A 31 31 30  3..112..REd..110
  00000010  0D 0A 67 72 65 65 6E 0D 0A 0D 0A 23 35 2F 30 39  ..green....#5/09
  00000020  2F 32 30 31 34 0D 0A 35 30 38 37 20 2D 20 35 2F  /2014..5087 - 5/
  00000030  36 2F 32 30 31 34 0D 0A                          6/2014..
  </code></pre>
  
  <p>After the fread, GDB prints fileCharacterBuffer as:</p>
  
  <pre><code>"3\n112\nREd\n110\ngreen\n\n#5/09/2014\n5087 - 5/6/2014\n", '\000' &lt;repeats 51 times&gt;
  </code></pre>
  
  <p>With only the \n's present. What?</p>