title: Read and write multiple line data file in C
body: <p>I'm having trouble reading and writing more than one line of data from a file.  The problem is to read multiple lines of binary from a file and convert it to decimal and write the multiple lines of decimal to a new file.  I had no problem getting the program to convert one line of binary to decimal the trouble comes when I have multiple lines.  Here is my code so far:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #define NULL 0
  
  int main() {
    FILE *ptdata, *ptresult;
    char bin[32];
    int i, r = 0, len;
    ptdata = fopen("data.txt", "r");
    ptresult = fopen("result.txt", "w");
    if (ptdata == NULL) printf("Error cannot open file");
    else {
      while (fgets(bin, 32, ptdata) != NULL);
      len = strlen(bin);
      for (i = 0; i &lt; len; i++) {
        r = r * 2 + (bin[i] == '1' ? 1 : 0);
      }
      printf("%d\n", r);
      fprintf(ptresult, "%d\n", r);
      fclose(ptdata);
      fclose(ptresult);
    }
    return 0;
  }
  </code></pre>