title: Opening a file with binary mode for processing
body: <p>What I am basically doing is opening a file in binary mode, dumping it into a buffer, and processing it, and I finally realized that opening the file in binary mode is causing a problem and I searched a bit on google but I don't know how to fix it.</p>
  <p>The code's aim is to reduce the number of lines. Note: The logic of the program is correct.</p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int foo(const char *filename);
  
  int main(void)
  {
      foo(&quot;file.txt&quot;);
  
      fputs(&quot;Press any key to continue...&quot;, stderr);
      getchar();
      return 0;
  }
  
  int foo(const char *filename)
  {
      /* open file in binary mode */
      FILE *fp = fopen(filename, &quot;rb&quot;);
      if (!fp) {
          perror(filename);
          return -1;
      }
  
      /* store file size and allocate memory accordingly */
      long f_size;
      fseek(fp, 0L, SEEK_END);
      f_size = ftell(fp);
      fseek(fp, 0L, SEEK_SET);
      char *buf = (char *)malloc(f_size+1);
      if (!buf) {
          puts(&quot;Error - malloc failed.&quot;);
          return -2;
      }
  
      /* store file contents in buffer */
      size_t bytes_read = fread(buf, 1, f_size, fp);
      if (bytes_read != f_size) {
          fclose(fp);
          free(buf);
          puts(&quot;read error...&quot;);
          return -3;
      }
      else {
          fclose(fp);
          buf[f_size] = '\0';
      }
  
      bool f = 0;
      size_t n = 0;
      size_t m = 0;
      while (buf[n]) {
          if (buf[n] == '\n') {
              if (f) {
                  f = 0;
                  buf[m++] = '\n';
              }
          }
          else {
              f = 1;
              buf[m++] = buf[n];
          }
          n++;
      }
      /* NUL-terminate buffer at m*/
      buf[m] = '\0';
  
      /* open file for writing */
      fp = fopen(filename, &quot;wb&quot;);
      if (!fp) {
          perror(filename);
          free(buf);
          return -4;
      }
  
      /* write buffer to file */
      size_t bytes_written = fwrite(buf, 1, m, fp);
      if (bytes_written != m) {
          puts(&quot;fwrite error...&quot;);
      }
      fclose(fp);
      free(buf);
      return 0;
  }
  </code></pre>
  <p>file.txt:</p>
  <blockquote>
  <p>00000000</p>
  <p>00000000</p>
  <p>00000000</p>
  </blockquote>
  <p>desired output:</p>
  <blockquote>
  <p>00000000<br />
  00000000<br />
  00000000</p>
  </blockquote>