title: Writing hex representation to file
body: <p>In my program, I am trying to read data from binary file, and then write it's hex representation to txt file.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int counter = 0;
  int read;
  int i = 0;
  long size;
  FILE *file1 = NULL; 
  FILE *file2 = NULL; 
  fpos_t length;
  char newLine = '\n';
  
  int main(int argc, char **argv) {
  
      if (argc &lt; 2) {
      printf("Use: %s file1 file2", argv[0]);
      exit (-1);
      }
  
      unsigned char hex[513];
      unsigned char buffer[257];
      file1 = fopen(argv[1], "rb");
      fseek(file1, 0, SEEK_END);
      fgetpos(file1, &amp;length);
      size = length.__pos;
      fseek(file1, 0, SEEK_SET); 
      if (file1) {
              file2 = fopen(argv[2], "w");
              if (!file2) {
                      printf("Cannot open file: %s\n", argv[2]);
                      exit(-1);
              }
              while (counter &lt; size) {
                      read = fread(buffer, 1, 256, file1);
                      counter += read;
                      i = 0;
                      while (i &lt; read) {
                              sprintf(hex, "%02x",  buffer[i++]);
                      }
                      fwrite(hex, 1, 512, file2);
                      fwrite(&amp;newLine, 1, 1, file2);
                      }
      } else
             printf("Cannot open file %s\n", argv[1]);
      fclose(file1);
      fclose(file2);
  }
  </code></pre>
  
  <p>Unfortunately data don't write to txt file properly. Please help me find my mistake. What is wrong in this code?</p>